4

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 the proper way of getting immediate feedback from a script, or is there a better way?

I mainly want this for debugging. I had a hang and was trying to find where the code stalled, but since my print statements didn't show up I was searching in the wrong place, thinking my code didn't get to the print statement. (I finally found it with breakpoints, which is perhaps a better way of debugging, but print immediate-prints are just more convenient sometimes.)

The Oddler
  • 6,314
  • 7
  • 51
  • 94

2 Answers2

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.

Mike Ounsworth
  • 2,444
  • 21
  • 28
1

The print has some arguments, like flush, so you can use flush=True to flush immediately.

See: https://realpython.com/python-flush-print-output

Regisz
  • 481
  • 9
  • 17