Python 2.7回车倒计时
我在python中使用回车实现简单的倒计时时遇到了问题。我有两个版本,每个版本都有问题 印刷版:Python 2.7回车倒计时,python,python-2.7,carriage-return,sys,Python,Python 2.7,Carriage Return,Sys,我在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 Co
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秒后,它只会将倒计时:9打印到屏幕上。我可以看到
\r
在幕后工作,但如何让打印在睡眠中穿插?对于解决方案2,您需要刷新标准输出
for i in range(10):
sys.stdout.write("\rCountdown: %d" % i)
sys.stdout.flush()
time.sleep(1)
print ''
另外,只需打印一个空字符串,因为print将附加换行符。或者使用print'\n',
,如果您认为它更可读,因为尾随的逗号会抑制通常附加的换行符
不确定如何修复第一个问题…另一个解决方案:
for i in range(10):
print "Countdown: %d\r" % i,
time.sleep(1)
对于解决方案1(打印版本),在Print语句末尾包含逗号将阻止在末尾打印换行符,如中所示。但是,如上所述,stdout仍然需要冲洗
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)
处理无:
我用
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
import time
for i in range(0,10):
print "countdown: ",10-i
time.sleep(1)
print chr(12)#clear screen
print "lift off"