此代码按预期工作.输出:
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
语句产生影响.