Python循环在窗口的解释器中不断停止

2024-10-06 12:22:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Windows中使用默认的Python 3.8解释器

每当我在其中运行一个长循环时,它就会停止,我必须按下或按住Enter键才能继续运行。这在Linux中从来都不是问题

如何修复此行为

# this loop will eventually stop/hang/pause forever, until I press the Enter key
for i in range(5000):
   time.sleep(1)
   print(i)

如果我通过任何IDE运行代码,它不会暂停。但是出于我自己的原因,我想直接在解释器中运行这个特定的代码

我在等待了超过1分钟之后拍摄了这个截图。这不是一次性的问题。我运行的任何循环,无论大小或复杂程度如何,都会在几次迭代后永久停止,直到我按下键盘上的ENTER键

enter image description here

enter image description here

enter image description here


Tags: 代码looplinuxwindowsthis解释器willuntil
3条回答

你所展示的程序实际上什么都不会做。它不会将任何内容打印到控制台,也不会等待输入

因此,它将实际运行83分钟,没有显示它正在做任何事情,然后它将退出,退出代码为0

我猜你遇到了什么

当然,程序会继续运行,但您只是没有看到输出,因为输出是缓冲的,您不会刷新它

因此,在每个print(i)之后,调用函数flush_output_streams()

def flush_output_streams() -> None:
    """
    flushes the output streams.

    flush calls are wrapped in try ... except, because 
    standard streams might be replaced with other streams which 
    dont have the flush method.
    """
    try:
        sys.stdout.flush()
    except Exception:
        pass
    try:
        sys.stderr.flush()
    except Exception:
        pass

如果单击输出,控制台将暂停脚本,它将尝试停止代码以“选择”输出的一部分。尝试一下,不要点击它。ENTER将从控制台上的选择栏中删除焦点,因此您将看到它不再存在

相关问题 更多 >