Skip to content Skip to sidebar Skip to footer

Print \r Correctly In Console

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 this script using the terminal (Ubuntu),

Solution 1:

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)

Solution 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.


Post a Comment for "Print \r Correctly In Console"