Python 2.7 carriage return countdown
Asked Answered
B

5

5

I'm having trouble implementing a simple countdown in python using a carriage return. I have two versions, each with problems.

Print Version:

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

Problem: The \r doesn't do anything because a newline is printed at the end, so it gives the output:

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 the sleep happens at the beginning, and after 10 seconds of sleep it just prints Countdown: 9 to the screen. I can see the \r is working behind the scenes, but how do I get the prints to be interspersed in the sleep?

Bechtold answered 2/7, 2013 at 21:37 Comment(0)
C
8

For solution number 2, you need to flush stdout.

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

Also, just print an empty string since print will append the newline. Or use print '\n' , if you think it is more readable as the trailing comma suppresses the newline that would typically be appended.

Not sure how to fix the first one though...

Checkbook answered 3/7, 2013 at 3:32 Comment(0)
E
1

For solution 1 (the Print Version), including a comma at the end of the print statement will prevent a newline from being printed at the end, as indicated in the docs. However, stdout still needs to be flushed as Brian mentioned.

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

An alternative is to use the print function, but sys.stdout.flush() is still needed.

from __future__ import print_function
for i in range(10):
    print("\rCountdown: %d" % i, end="")
    sys.stdout.flush()
    time.sleep(1)
Extraterritorial answered 2/8, 2018 at 3:19 Comment(0)
A
1

I use

import time
for i in range(0,10):
    print "countdown: ",10-i
    time.sleep(1)    
    print chr(12)#clear screen
print "lift off"
Assumption answered 10/5, 2020 at 20:30 Comment(0)
R
-1

HANDLE NONE:

for i in xrange(10):
    print "COUNTDOWN: %d" %i, time.sleep(1)

# OP
# Countdown: 0 None
# Countdown: 1 None
# Countdown: 2 None
# Countdown: 3 None
# Countdown: 4 None
# Countdown: 5 None
# Countdown: 6 None
# Countdown: 7 None
# Countdown: 8 None
# Countdown: 9 None
Rockabilly answered 2/8, 2018 at 7:25 Comment(0)
I
-2

Another solution:

for i in range(10):
    print "Countdown: %d\r" % i,
    time.sleep(1)
Irvin answered 10/9, 2013 at 13:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.