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

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?

Mik*_*ler 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
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)

从命令行运行unbuffered

你可以删除该行:

sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)

如果您使用以下-u选项运行脚本:

python -u script_name.py
Run Code Online (Sandbox Code Playgroud)

注意:这将对所有print语句产生影响.