How to overwrite the previous print to stdout in python?

后端 未结 16 1427
别那么骄傲
别那么骄傲 2020-11-22 09:46

If I had the following code:

for x in range(10):
     print x

I would get the output of

1
2
etc..

What I

相关标签:
16条回答
  • 2020-11-22 10:27

    Better to overwrite the whole line otherwise the new line will mix with the old ones if the new line is shorter.

    import time, os
    for s in ['overwrite!', 'the!', 'whole!', 'line!']:
        print(s.ljust(os.get_terminal_size().columns - 1), end="\r")
        time.sleep(1)
    

    Had to use columns - 1 on Windows.

    0 讨论(0)
  • 2020-11-22 10:31

    @Mike DeSimone answer will probably work most of the time. But...

    for x in ['abc', 1]:
        print '{}\r'.format(x),
    
    -> 1bc
    

    This is because the '\r' only goes back to the beginning of the line but doesn't clear the output.

    EDIT: Better solution (than my old proposal below)

    If POSIX support is enough for you, the following would clear the current line and leave the cursor at its beginning:

    print '\x1b[2K\r',
    

    It uses ANSI escape code to clear the terminal line. More info can be found in wikipedia and in this great talk.

    Old answer

    The (not so good) solution I've found looks like this:

    last_x = ''
    for x in ['abc', 1]:
        print ' ' * len(str(last_x)) + '\r',
        print '{}\r'.format(x),
        last_x = x
    
    -> 1
    

    One advantage is that it will work on windows too.

    0 讨论(0)
  • 2020-11-22 10:32

    I had the same question before visiting this thread. For me the sys.stdout.write worked only if I properly flush the buffer i.e.

    for x in range(10):
        sys.stdout.write('\r'+str(x))
        sys.stdout.flush()
    

    Without flushing, the result is printed only at the end out the script

    0 讨论(0)
  • 2020-11-22 10:32

    I couldn't get any of the solutions on this page to work for IPython, but a slight variation on @Mike-Desimone's solution did the job: instead of terminating the line with the carriage return, start the line with the carriage return:

    for x in range(10):
        print '\r{0}'.format(x),
    

    Additionally, this approach doesn't require the second print statement.

    0 讨论(0)
  • 2020-11-22 10:33

    Since I ended up here via Google but am using Python 3, here's how this would work in Python 3:

    for x in range(10):
        print("Progress {:2.1%}".format(x / 10), end="\r")
    

    Related answer here: How can I suppress the newline after a print statement?

    0 讨论(0)
  • 2020-11-22 10:33

    I'm a bit surprised nobody is using the backspace character. Here's one that uses it.

    import sys
    import time
    
    secs = 1000
    
    while True:
        time.sleep(1)  #wait for a full second to pass before assigning a second
        secs += 1  #acknowledge a second has passed
    
        sys.stdout.write(str(secs))
    
        for i in range(len(str(secs))):
            sys.stdout.write('\b')
    
    0 讨论(0)
提交回复
热议问题