此代码按预期方式工作。输出:
Loading
Loading.
Loading..
Loading...
码:
done = False
count = 0
while not done:
print '{0}\r'.format("Loading"),
time.sleep(0.25)
print '{0}\r'.format("Loading."),
time.sleep(0.25)
print '{0}\r'.format("Loading.."),
time.sleep(0.25)
print '{0}\r'.format("Loading..."),
time.sleep(0.25)
count += 1
if count == 5:
done = True
而且此代码没有。输出:
Loading.
Loading...
码:
done = False
count = 0
while not done:
print '{0}\r'.format("Loading"),
time.sleep(0.125)
print '{0}\r'.format("Loading."),
time.sleep(0.125)
print '{0}\r'.format("Loading.."),
time.sleep(0.125)
print '{0}\r'.format("Loading..."),
time.sleep(0.125)
count += 1
if count == 5:
done = True
如果时间函数print
小于0.25,为什么时间函数似乎每隔一秒就会跳过一次?
根据平台的不同,Python会将输出缓冲到不同的程度。例如,在Mac OSX上,即使您的睡眠时间为0.25秒,也根本没有输出。
手动冲洗应起作用:
import sys
import time
done = False
count = 0
while not done:
for n in range(4):
print '{0}\r'.format("Loading" + n * '.'),
sys.stdout.flush()
time.sleep(0.125)
print ' ' * 20 + '\r',
count += 1
if count == 5:
done = True
您需要使用刷新输出sys.stdout.flush()
。您还需要打印空白以使点“来回移动”:
print ' ' * 20 + '\r',
就显示的文字而言,这被缩短了,并且更加通用:
import sys
import time
text = 'Loading'
for _ in range(5):
for n in range(4):
print '{0}\r'.format(text + n * '.'),
sys.stdout.flush()
time.sleep(0.25)
nspaces = len(text) + n
print ' ' * nspaces + '\r',
您可以删除以下行:
sys.stdout.flush()
如果使用以下-u
选项运行脚本:
python -u script_name.py
注意:这将影响所有print
语句。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句