multiple prints on the same line in Python

前端 未结 17 2285
独厮守ぢ
独厮守ぢ 2020-11-22 06:06

I want to run a script, which basically shows an output like this:

Installing XXX...               [DONE]

Currently, I print Installi

17条回答
  •  失恋的感觉
    2020-11-22 06:18

    You should use backspace '\r' or ('\x08') char to go back on previous position in console output

    Python 2+:

    import time
    import sys
    
    def backspace(n):
        sys.stdout.write((b'\x08' * n).decode()) # use \x08 char to go back   
    
    for i in range(101):                        # for 0 to 100
        s = str(i) + '%'                        # string for output
        sys.stdout.write(s)                     # just print
        sys.stdout.flush()                      # needed for flush when using \x08
        backspace(len(s))                       # back n chars    
        time.sleep(0.2)                         # sleep for 200ms
    

    Python 3:

    import time   
    
    def backline():        
        print('\r', end='')                     # use '\r' to go back
    
    
    for i in range(101):                        # for 0 to 100
        s = str(i) + '%'                        # string for output
        print(s, end='')                        # just print and flush
        backline()                              # back to the beginning of line    
        time.sleep(0.2)                         # sleep for 200ms
    

    This code will count from 0% to 100% on one line. Final value will be:

    > python test.py
    100%
    

    Additional info about flush in this case here: Why do python print statements that contain 'end=' arguments behave differently in while-loops?

提交回复
热议问题