我在使用回车在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: 9Sys.stdout.write版本:
for i in range(10):
sys.stdout.write("\rCountdown: %d" % i)
time.sleep(1)
print "\n"问题:所有的睡眠都是在开始时发生的,在睡眠10秒后,它只会将Countdown: 9打印到屏幕上。我可以看到\r在幕后工作,但是如何让指纹散布在睡眠中呢?
发布于 2013-07-03 11:32:54
对于解决方案2,您需要刷新stdout。
for i in range(10):
sys.stdout.write("\rCountdown: %d" % i)
sys.stdout.flush()
time.sleep(1)
print ''另外,只打印一个空字符串,因为print会附加换行符。或者,如果您认为print '\n' ,更具可读性,则可以使用它,因为尾随逗号会抑制通常会附加的换行符。
虽然不确定如何修复第一个问题...
发布于 2018-08-02 11:19:14
对于解决方案1(打印版本),在打印语句的末尾包含一个逗号将阻止在末尾打印换行符,如docs所示。但是,正如Brian所提到的,仍然需要刷新标准输出。
for i in range(10):
print "\rCountdown: %d" % i,
sys.stdout.flush()
time.sleep(1)另一种方法是使用print function,但仍然需要sys.stdout.flush()。
from __future__ import print_function
for i in range(10):
print("\rCountdown: %d" % i, end="")
sys.stdout.flush()
time.sleep(1)发布于 2020-05-11 04:30:35
我使用
import time
for i in range(0,10):
print "countdown: ",10-i
time.sleep(1)
print chr(12)#clear screen
print "lift off"https://stackoverflow.com/questions/17436240
复制相似问题