Python 2.7 回车倒计时

5

我有一个问题,想要在Python中使用回车实现一个简单的倒计时。我有两个版本,但每个版本都有问题。

打印版:

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

问题:由于在结尾处打印了换行符,因此\r没有任何作用,因此输出如下:
Countdown: 0
Countdown: 1
Countdown: 2
Countdown: 3
Countdown: 4
Countdown: 5
Countdown: 6
Countdown: 7
Countdown: 8
Countdown: 9

Sys.stdout.write版本:

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

问题:所有的睡眠都发生在开始,而在睡眠10秒后,它只是将Countdown: 9打印到屏幕上。我可以看到\r在幕后起作用,但我该如何让打印在睡眠中间交替出现?
5个回答

8
对于解决方案2,您需要刷新标准输出。
for i in range(10):
    sys.stdout.write("\rCountdown: %d" % i)
    sys.stdout.flush()
    time.sleep(1)
print ''

此外,只需打印一个空字符串即可,因为print会自动添加换行符。或者使用print '\n' ,,如果您认为这样更易读,因为尾逗号将抑制通常会被添加的换行符。不过,我不确定如何解决第一个问题...

1
对于解决方案1(打印版本),在打印语句的末尾包含逗号可以防止换行符被打印在末尾,如docs中所示。然而,stdout仍需要刷新,正如Brian所提到的。
for i in range(10):
    print "\rCountdown: %d" % i,
    sys.stdout.flush()
    time.sleep(1)

另一种选择是使用打印函数,但仍需要sys.stdout.flush()

from __future__ import print_function
for i in range(10):
    print("\rCountdown: %d" % i, end="")
    sys.stdout.flush()
    time.sleep(1)

1

我使用

import time
for i in range(0,10):
    print "countdown: ",10-i
    time.sleep(1)    
    print chr(12)#clear screen
print "lift off"

-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

-2

另一种解决方案:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接