为什么time()低于0.25会在Python中跳过动画?

时间:2016-01-06 12:58:04

标签: python python-2.7 time stdout

此代码按预期工作。输出:

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?

1 个答案:

答案 0 :(得分:5)

原因

根据平台的不同,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语句产生影响。