【问题标题】:Why time() below 0.25 skips animation in Python?为什么低于 0.25 的 time() 会跳过 Python 中的动画?
【发布时间】:2016-01-06 12:58:04
【问题描述】:

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

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 语句?

【问题讨论】:

  • 奇怪,它可以在我的机器上运行。也许它取决于操作系统。我使用的是 Windows 7。您使用的是什么操作系统?
  • 我没有这个问题,我得到了Loading Loading. Loading.. Loading...,但很可能与您的回车有关。
  • 好像和输出缓冲有关,不同机器上效果会有很大差异。例如,它根本没有在我的机器上打印任何东西。 :-)
  • 如果你导入打印函数或切换到 Python 3,你可以只使用flush=True 而不是显式调用sys.stdout.flush()
  • @TigerhawkT3:您不能使用__future__ 导入来获得Py2 中的flush=True 支持; flush 参数仅添加到 Py 3.3 中的 print 函数中,并且从未向后移植到 2.x 行。

标签: python python-2.7 time stdout


【解决方案1】:

原因

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

【讨论】:

  • 使用终端尺寸可能更简洁,而不是打印 20 个空格:width = struct.unpack('HHHH', fcntl.ioctl(0, termios.TIOCGWINSZ, struct.pack('HHHH', 0, 0, 0, 0)))[1]
  • @ThiefMaster 对我来说看起来很复杂。 print ' ' * nspaces + '\r', 是不是简单一点?我使用它我的清理版本。
  • hrm 是的,在这种情况下肯定更容易。在实际应用程序中,您可以将其作为 term_size 函数放在 util 模块中,或者甚至提供一个 clear_line() 函数来打印 \r 和正确数量的空格
  • 它在 PyCharm 中不起作用,但在 Python 中起作用,所以应该没问题。感谢您的帮助并向我解释这一点。
猜你喜欢
  • 2023-02-06
  • 1970-01-01
  • 1970-01-01
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-25
相关资源
最近更新 更多