Question

I was following a little tutorial and after much research, I can't figure out why the given code doesn't print on the same line. I copied it directly, so it should work.

import time
import sys
sys.stdout.write('29 seconds remaining')
time.sleep(1)
sys.stdout.write('\r28 seconds remaining')

Output is:

29 seconds remaining
28 seconds remaining

Final output should be:

28 seconds remaining
Was it helpful?

Solution

I put the "\r" at the end of the line, not at the front. Like this:

 sys.stdout.write("%s[%s%s] %2i/%i\r" % (variables go here))
 sys.stdout.flush()

OTHER TIPS

After trying out solutions that seemed to work for others with the same setup like me, I had to find out the hard way that carriage return sequences are parsed by the shell that outputs the printed string (please correct me here if not precise enough). I started getting closer to the solution when i realised that the windows command prompt (C:\Windows\System32\cmd.exe) actually interpreted the carriage return as expected, but the PyScripter IDE did not. Then I realised that the PyScripter developers new about this, but did not want to spend the effort of mimicking the cmd.exe behaviour.

Hope this puts fellow developers in the right direction and will save some time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top