简体   繁体   English

为什么 python 在 time.sleep() 之后不打印?

[英]Why python don't print after a time.sleep()?

I'm programming in python for almost 2 years and I found a really weird thing when watching some old code.我在 python 编程了将近 2 年,在看一些旧代码时发现了一件非常奇怪的事情。

import random, sys, time

try:
    while True:
        print(' ', str(random.randint(100,999)), end='')
        time.sleep(0.01)
except:
    sys.exit()

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.按照这段代码的语法,我的程序应该永远打印一个空格和一个从 100 到 999 的随机数,但这并没有发生。

When I run this code nothing appear on the screen until I press CTRL-C, even removing the try statement din't change anything.当我运行这段代码时,屏幕上什么都不会出现,直到我按下 CTRL-C,即使删除 try 语句也不会改变任何东西。

I tried changing console (Windows terminal, powershell and CMD) but nothing happened.我尝试更改控制台(Windows 终端、powershell 和 CMD)但什么也没发生。

Can please someone help me out with this?请有人帮我解决这个问题吗? Thanks谢谢

This answer Python sleep() inhibit print with comma?这个答案Python sleep() 用逗号禁止打印? suggests adding sys.stdout.flush() between the print and the sleep .建议在printsleep之间添加sys.stdout.flush() Tested it - works.测试它 - 有效。

Python keeps your print outputs in a buffer and waits for the end of the line before actually displaying it. Python 将打印输出保存在缓冲区中,并在实际显示之前等待行尾。 To force the display in Python 3, you can add the keyword flush=True .要在 Python 3 中强制显示,可以添加关键字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()

Alternatively, you can:或者,您可以:

  • call sys.stdout.flush() after the print (Python 2-compatible);打印后调用sys.stdout.flush() (Python 2 兼容);
  • use the -u flag when executing the script ( python -u script.py );执行脚本时使用-u标志( python -u script.py );
  • set the environment variable PYTHONUNBUFFERED to TRUE .将环境变量PYTHONUNBUFFERED设置为TRUE

Which version of PYTHON are you using?您使用的是哪个版本的PYTHON I was able to run your code in my PC where I am using PYTHON 3.7 in PYCHARM 2019.2.4 .我能够在我的 PC 上运行您的代码,我在PYCHARM 2019.2.4中使用PYTHON 3.7
It also ran successfully on PYTHON 3.7.5 shell它还在PYTHON 3.7.5 shell上成功运行

Try this:尝试这个:

import random, sys, time
try:
    while True:
        print(' ', str(random.randint(100,999)), end='', flush=True)
        time.sleep(1)
except:
    sys.exit()

This is because you have a while True clause that's looping forever, Causing it loop recursively infinitely.这是因为您有一个永远循环的while True子句,导致它无限递归地循环。

Here is the updated code这是更新的代码

import random, sys, time

try:
    while True:
        print(' ', str(random.randint(100,999)), end='')
        time.sleep(0.01)
        break
except:
    sys.exit()

I added a break statement to move to get out of the loop.我添加了一个break语句来跳出循环。

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

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