简体   繁体   English

time.sleep() 函数不起作用

[英]time.sleep() function not working

I'm using time.sleep() in a program but the lines seem to be running out of order.我在程序中使用 time.sleep() 但线路似乎运行不正常。 Here is the code:这是代码:

print("Line 1")
time.sleep(1)
print("Line 2")
time.sleep(1)
print("Line 3")
time.sleep(1)

And it runs like this:它像这样运行:

(waits) Line 1 Line 2 (waits) Line 3 (等待)第 1 行 第 2 行(等待)第 3 行

Instead of:而不是:

Line 1 (waits) Line 2 (waits) Line 3 (waits)第 1 行(等待) 第 2 行(等待) 第 3 行(等待)

I've had this problem with a lot of programs that I use this function for, never really found a fix.我在使用此功能的许多程序中都遇到了这个问题,但从未真正找到解决方法。 Any suggestions?有什么建议吗?

Try running without output buffering, ie python -u foo.py .尝试在没有输出缓冲的情况下运行,即python -u foo.py You can also try to call sys.stdout.flush() after every print , just to test it.您也可以尝试在每次print之后调用sys.stdout.flush() ,只是为了测试它。

Instead of time.sleep() , use sleep() : 代替time.sleep() ,使用sleep()

from time import sleep
print("Line 1")
sleep(1)
print("Line 2")
sleep(1)
print("Line 3")
sleep(1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM