How do I force Python\'s print function to output to the screen?
This is not a duplicate of Disable output buffering - the linked question is attempting unbuffe
Using the -u command-line switch works, but it is a little bit clumsy. It would mean that the program would potentially behave incorrectly if the user invoked the script without the -u option. I usually use a custom stdout, like this:
class flushfile:
def __init__(self, f):
self.f = f
def write(self, x):
self.f.write(x)
self.f.flush()
import sys
sys.stdout = flushfile(sys.stdout)
... Now all your print calls (which use sys.stdout implicitly), will be automatically flushed.