Gun*_*nnm 5 python time stdout python-2.7
此代码按预期工作.输出:
Loading
Loading.
Loading..
Loading...
Run Code Online (Sandbox Code Playgroud)
码:
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
Run Code Online (Sandbox Code Playgroud)
而这段代码没有.输出:
Loading.
Loading...
Run Code Online (Sandbox Code Playgroud)
码:
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
Run Code Online (Sandbox Code Playgroud)
为什么时间函数似乎跳过每一个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
Run Code Online (Sandbox Code Playgroud)
你需要刷新输出sys.stdout.flush()
.您还需要打印空白区域以使点"来回":
print ' ' * 20 + '\r',
Run Code Online (Sandbox Code Playgroud)
这缩短了,并且在显示的文本方面更加通用:
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',
Run Code Online (Sandbox Code Playgroud)
你可以删除该行:
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
如果您使用以下-u
选项运行脚本:
python -u script_name.py
Run Code Online (Sandbox Code Playgroud)
注意:这将对所有print
语句产生影响.
归档时间: |
|
查看次数: |
135 次 |
最近记录: |