为什么python在time.sleep()之后不打印? [英] Why python don't print after a time.sleep()?
问题描述
我用 python 编程将近 2 年了,我在看一些旧代码时发现了一个非常奇怪的事情.
I'm programming in python for almost 2 years and I found a really weird thing when watching some old code.
import random, sys, time
try:
while True:
print(' ', str(random.randint(100,999)), end='')
time.sleep(0.01)
except:
sys.exit()
按照这段代码的语法,我的程序应该永远打印一个空格和一个从 100 到 999 的随机数,但这并没有发生.
Following the syntax of this code my program should print a space and a random number from 100 to 999 forever, but this isn't happening.
当我运行这段代码时,在我按下 CTRL-C 之前,屏幕上什么都没有出现,即使删除了 try 语句也不会改变任何东西.
When I run this code nothing appear on the screen until I press CTRL-C, even removing the try statement din't change anything.
我尝试更改控制台(Windows 终端、powershell 和 CMD),但没有任何反应.
I tried changing console (Windows terminal, powershell and CMD) but nothing happened.
有人可以帮我解决这个问题吗?谢谢
Can please someone help me out with this? Thanks
推荐答案
Python 将打印输出保存在缓冲区中,并在实际显示之前等待行尾.要在 Python 3 中强制显示,可以添加关键字 flush=True
.
Python keeps your print outputs in a buffer and waits for the end of the line before actually displaying it.
To force the display in Python 3, you can add the keyword flush=True
.
import random, sys, time
try:
while True:
print(' ', str(random.randint(100,999)), end='', flush=True)
time.sleep(0.01)
except:
sys.exit()
或者,您可以:
- 在打印后调用
sys.stdout.flush()
(Python 2 兼容); - 在执行脚本时使用
-u
标志 (python -u script.py
); - 将环境变量
PYTHONUNBUFFERED
设置为TRUE
.
- call
sys.stdout.flush()
after the print (Python 2-compatible); - use the
-u
flag when executing the script (python -u script.py
); - set the environment variable
PYTHONUNBUFFERED
toTRUE
.
这篇关于为什么python在time.sleep()之后不打印?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!