python - 为什么这个计时器只打印最终结果而不是每秒更新一次?

标签 python terminal carriage-return

我不明白为什么这段代码的第二部分不是以 1 秒的步长打印一个数字,而是全部在脚本的末尾(在本例中是在第二部分开始后 3 秒)代码)?

#!/usr/bin/python2.7

import time

x       =   0
maxi    =   999999 #I chose a big number to show them scroll

#this part will print all the number on the same line
while x <= maxi:
    print '<{}>\r'.format(x),
    x+=1
print

#this part will print the numbers with a sleep of 1 second for each print
x       =   999998 #I initialized it at this number to only wait 3 seconds
while x <= maxi:
    print '<{}>\r'.format(x),
    x+=1
    time.sleep(1)
print

最佳答案

这可能是因为缓冲。 您可以尝试在命令行上使用 python -u 运行程序,如手册页所述

-u Force stdin, stdout and stderr to be totally unbuffered. [...]

或者您可以使用import sys并在print()之后放置一个sys.stdout.flush()

如果您想知道为什么第二次打印需要这样,而不是第一次打印需要这样,很可能是因为 sleep 。它会阻止执行,因此不会更新/刷新任何内容。我认为这实际上也发生在第一个上,但更新更多/更快,所以你不会注意到它。

关于python - 为什么这个计时器只打印最终结果而不是每秒更新一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40407019/

相关文章:

python - Pycharm 中的 """input().split() in loop"""问题

c - 为什么 fgets 卡在回车\r 上?

python - add_subparsers 无法识别 sub_argument

python - 如何使用 google docs api (Python) 更新 google doc

Python Selenium 未加载整页源代码

java\r 字符在 Eclipse 中不起作用

php - 如何使用php删除html中的回车符?

python - Python 3中True和False的不同对象大小

git - 如何通过从终端运行命令来打开指向我的 Github 存储库的链接?

python - 如何从 django 的子目录中打开终端