using flush=True
only makes python flush the data in its "application buffer" to the "OS buffers", but it doesn't ensure that the operating system buffers are flushed to disk/screen.
if you are outputting the results to a file (or using a few IDEs), then in order to flush those buffers you have to issue a system call using os.fsync which calls the OS to flush its own buffers to their final destination (disk/screen), this is a slow operation which involves a system call so it shouldn't be used carelessly after every print.
import sys
import os
print("INFO", flush=True, file=sys.stdout)
os.fsync(sys.stdout.fileno())
print("ERROR", flush=True, file=sys.stderr)
os.fsync(sys.stderr.fileno())
in case you were running this in a terminal you should wrap os.fsync
in a try/except block for OSError
(preferably with contextlib.suppress(OSError)).
note that some IDEs implement their own logic for reading file descriptors, so it may not work for all IDEs.
For pycharm on linux/macos there is a bug that was reported in 2013 and still not fixed about this problem (because it's practically not fixable), a workaround is to direct stderr to stdout, and lose the red coloring, this is applicable to any IDE that manually handles stdout buffers and hence produces this bug. (or sleep for 1 millisecond to force a context switch by the OS, but that's not practical)
import sys
import os
os.dup2(sys.stdout.fileno(),sys.stderr.fileno()) # redirect os stderr buffers to stdout
sys.stderr = sys.stdout # redirect python stderr buffers to stdout
print("INFO", flush=True, file=sys.stdout)
print("ERROR", flush=True, file=sys.stderr)