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?
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 print
ed 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..