【发布时间】:2023-01-02 08:05:04
【问题描述】:
以下 python 程序的输出有时会乱序:
print("Dividing 0 by 0...")
res = 0/0
->
Traceback (most recent call last):
File "[...]/scratches/scratch_8.py", line 2, in <module>
res = 0/0
ZeroDivisionError: division by zero
Dividing 0 by 0...
在我阅读以下主题后:Disable output buffering、How can I flush the output of the print function? 和Python's print function that flushes the buffer when it's called?, 我将程序更改为:
print("Dividing 0 by 0...", flush = True)
res = 0/0
但是,它仍然偶尔会乱序打印输出。为什么 flush = True 选项没有显示它的效果?
【问题讨论】:
-
您是否对第一行未执行感到困惑?真是太神奇了。也许您应该粘贴终端刷新的全部内容。
-
第一行总是被执行。但是,输出偶尔会出现在异常消息之后。我知道 python IO 是缓冲的,因此我包括了
flush = True。但我不明白的是,为什么它仍然不起作用。 -
print和异常消息使用不同的流,stdout和stderr。异常消息也应该是无缓冲的,可能这就是为什么它有时不起作用的原因。基于this,如果符合您的要求,您可以考虑写入标准错误。 -
即使在
res = 0/0之前加上sys.stderr.flush(),输出还是偶尔会出现乱序。我按以下方式阅读了包括上面一行的程序:1.) 打印一条消息,然后刷新sys.stdout流。 2.) 刷新sys.stderr流,3.) 引发异常,将异常消息输出到sys.stderr。流未刷新。为什么这仍然不同步?不明白。
标签: python python-3.x exception printing output