Reputation: 385
I have a program in Python that makes extensive use of the line feed character to produce the effect of an updating console line (specifically a progress bar). When trying to debug the code in PyCharm I saw that the progress bar doesn't get printed until it's done.
Upon further inspection it turned out that when a carriage return (\r
) is printed, the whole line is deleted. Because the library itself writes strings of the form ({line}\r
), I always get an empty line.
Sample code:
import sys
sys.stdout.write('xxx')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('\rZZ')
sys.stdout.flush()
time.sleep(1)
sys.stdout.write('yyy\r')
sys.stdout.flush()
time.sleep(1)
print ('===')
My run looks like this:
xxx
is printedZZ
is printed===
is printed and the program terminatesThis happens both in the debug and the run console when running this script.
Upvotes: 9
Views: 7605
Reputation: 173
The answer is actually in your post. As you said, the carriage return deletes the whole line. To avoid the issue, print the carriage return only when you print the new line, like so:
Print each line with the carriage return at the start, and without the default end='\n'
. Didn't need the flush, though I didn't do much testing.
print('\rxxx', end='')
# sys.stdout.flush()
time.sleep(1)
Continue like this...
print('\rZZ', end='')
time.sleep(1)
print('\ryyy', end='')
time.sleep(1)
To keep the last printout, keep the default end.
print('\r===')
Upvotes: 9
Reputation: 140
The bug is still active and it was reported here. For now if you Use the Run > Configuration > "Emulate Terminal in Output Console" the carriage return will function as intended.
Upvotes: 6
Reputation: 327
Be careful with short time between prints and short length of printed strings, printing can be tricky and print few values in one row.
To workaround that you can add second \r after white character:
for i in range(10):
print("\r \r{0}".format(str(i)), end='')
time.sleep(0.1)
My solution for similar issue: https://stackoverflow.com/a/44524422/6857902
Upvotes: 2