1

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?

  • Are you confused about the first line is not executed? that's kind of amazing. Maybe you should paster the whole content flushed by the terminal. – 0to1toeverything Sep 06 '22 at 09:36
  • The first line is always executed. However, the output comes occasionally after the exception message. I understand that python IO is buffered, therefor I included `flush = True`. But what I do not understand is, why it still not works. – Wör Du Schnaffzig Sep 06 '22 at 09:42
  • `print` and exception message are using different streams, `stdout` and `stderr`. Exception message should be unbuffered too, probably that's why occasionally it doesn't work. Based on [this](https://stackoverflow.com/questions/59719872/why-does-python-print-exceptions-to-the-console-before-print-output), you can consider writing to standard error if it fits your requirement. – wavingtide Sep 06 '22 at 10:34
  • Even if adding `sys.stderr.flush()` before `res = 0/0`, the output is still occasionally out-of-order. I read the program including the line above in the following way: 1.) Print a msg, then flush the `sys.stdout` stream. 2.) Flush the `sys.stderr` stream, 3.) Raise exception, output exception msg to `sys.stderr`. Stream not flushed. Why is this still out of sync? Don't understand. – Wör Du Schnaffzig Sep 06 '22 at 11:44

1 Answers1

1

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

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153