Skip to content Skip to sidebar Skip to footer

Python Print Immediately?

I noticed that in python when I use a print statement, that it doesn't print immediately. I found you can use sys.stdout.flush() to make it show the print in the console. Is this t

Solution 1:

Exactly how and when stdout will flush itself depends on the implementation of the print function you're using, the string you're trying to print, possibly the OS, etc.

Anecdotally, stdout seems to flush when it hits a newline character, but I don't always trust it, or I won't know until runtime if my string will contain a newline, so I use flush() pretty regularly in C, Java, and Python when I want to be sure that something prints immediately and I am not overly concerned about performance. Places where I've found this especially useful (ie where timing of the messages really matters) is: near code that is likely to throw exceptions, right before blocking IO calls, in multi-threaded sections of code.

As a practical example, something like this seems like a natural usage for flush() (sorry it's in C++ rather than Python)

printf("Connecing to IP Camera at %s...", ipCamAddr);
cout.flush();

//open a network connection to the camera

printf("Done!\n");

Because without the flush, it would hold the first string until it gets a \n, which is after the connection has succeeded / failed.

Post a Comment for "Python Print Immediately?"