我不明白为什么这段代码的第二部分不是以 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/