Python 2.7 carriage return countdown

I am having trouble implementing a simple countdown in python using carriage return. I have two versions, each of which has problems.

Print version:

for i in range(10): print "\rCountdown: %d" % i time.sleep(1) 

Problem: \r does nothing, because a newline is printed at the end, so it displays the result:

 Countdown: 0 Countdown: 1 Countdown: 2 Countdown: 3 Countdown: 4 Countdown: 5 Countdown: 6 Countdown: 7 Countdown: 8 Countdown: 9 

Sys.stdout.write Version:

 for i in range(10): sys.stdout.write("\rCountdown: %d" % i) time.sleep(1) print "\n" 

Problem: All sleep occurs at the beginning, and after 10 seconds of sleep, it simply prints Countdown: 9 on the screen. I see that \r works behind the scenes, but how can I get fingerprints to be inserted in a dream?

+4
source share
2 answers

For solution number 2 you need to reset stdout.

 for i in range(10): sys.stdout.write("\rCountdown: %d" % i) sys.stdout.flush() time.sleep(1) print '' 

Alternatively, just print an empty line, as printing will add a new line. Or use print '\n' , if you think this is more readable, since the trailing comma suppresses the new line that is usually added.

I don’t know how to fix the first one, though ...

+7
source

Another solution:

 for i in range(10): print "Countdown: %d\r" % i, time.sleep(1) 
-1
source

Source: https://habr.com/ru/post/1489365/


All Articles