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

Why time() below 0.25 skips animation in Python?

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

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

如果时间函数低于 0.25,为什么它似乎每秒跳过 print 语句?

原因

根据平台的不同,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() 刷​​新输出。您还需要打印空格来制作点 "going back and forth":

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 语句产生影响。