Search code examples
pythonpython-3.xexceptionprintingoutput

Printing in Python before exception, output unordered


The output of the following python program my be occasionally out-of-order:

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...

After I read the following threads: Disable output buffering, How can I flush the output of the print function? and Python's print function that flushes the buffer when it's called?, I changed my program into:

print("Dividing 0 by 0...", flush = True)
res = 0/0

However, it still prints the output occasionally out-of-order. Why is the flush = True option not showing it's effect?


Solution

  • Why is the flush = True option not showing its effect?

    Because exception stack traces are not written to the same place as print output, by default. The printed message is sent to the program's standard output stream (sys.stdout), while errors appear on the standard error stream (sys.stderr).

    To get consistent output order, these streams need to be synchronized, not just flushed every time there is an output..