Print \r correctly in console

后端 未结 2 1779
無奈伤痛
無奈伤痛 2021-01-22 10:09

When I write a script that updates a printed line, for example like this:

for i in range(101):
    print(str(i) + \"% \\r\", end=\"\")

and run

相关标签:
2条回答
  • This seems to be the old CR LF problem. Depending on the OS and the console you are using, CR and LF as a line termination will be interpreted differently.

    Some systems require a CRLF as an end of line. Some systems only require LF but do the CR implicitly. Some systems (like yours) do a LF before each CR implicitly, although this is the first time I see this.

    Maybe there is a way to edit the newline settings for your PyDev console.

    EDIT: Or you might use ANSI escape codes for moving the cursor around. Like CSInD for n characters to the left or CSInC for n characters to the right.

    0 讨论(0)
  • 2021-01-22 10:31

    This is because 'print' always generates a new line whenever you use \r or not, try sys.stdout instead:

    import time, sys
    
    for i in range(101):
        sys.stdout.write(str(i) + "% \r")
        sys.stdout.flush()
        time.sleep(.3)
    
    0 讨论(0)
提交回复
热议问题