【问题标题】:Printing in Python before exception, output unordered在异常之前在 Python 中打印,输出无序
【发布时间】: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 bufferingHow 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 和异常消息使用不同的流,stdoutstderr。异常消息也应该是无缓冲的,可能这就是为什么它有时不起作用的原因。基于this,如果符合您的要求,您可以考虑写入标准错误。
  • 即使在res = 0/0之前加上sys.stderr.flush(),输出还是偶尔会出现乱序。我按以下方式阅读了包括上面一行的程序:1.) 打印一条消息,然后刷新sys.stdout流。 2.) 刷新sys.stderr流,3.) 引发异常,将异常消息输出到sys.stderr。流未刷新。为什么这仍然不同步?不明白。

标签: python python-3.x exception printing output


【解决方案1】:

为什么 flush = True 选项没有显示它的效果?

因为异常堆栈跟踪 are not written to the same place 作为 print 输出,默认情况下。 printed 消息被发送到程序的标准输出流 (sys.stdout),而错误出现在标准错误流 (sys.stderr) 上。

为了获得一致的输出顺序,这些流 need to be synchronized, not just flushed every time there is an output.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 1970-01-01
    • 2020-05-14
    • 2010-12-01
    • 2016-09-26
    相关资源
    最近更新 更多