Immediate display, forced display, flash of print output result with python (mainly jupyter)

background

To check the progress of heavy processing, the print statement inserted in the middle of processing is not output at that time It may come out all at once after the processing is completed.

This behavior may be correct in terms of processing speed, but This is a problem when you want it to be released immediately. ..

** Only jupyter? ** **

In the example sentence below, it happens with jupyter (IPython notebook), so it may depend on the buffer settings. On the console, even if flush was not specified, it was output sequentially.

Solution

  1. python3.3 or later: Forcibly spit out print output: Use flush option!
  2. Before python3.3 and 2.X: Use sys.stdout.flush () after print. (Operation unconfirmed)

** Add flush = True to the print function options! (python3.3 or later) **

python3.3 or later


print("", flush=True)

** Use sys.stdout.flush () after printing (operation unconfirmed) **

python3.Before 3(The code below is python2 series)


import sys
print ""
sys.stdout.flush()

** Example: with python3.4 and jupyter **

Confirmed with jupyter (On the console, it was output sequentially even without flushing ...)


import time
time.sleep(1)
print("processing A...")#Not displayed here ...
time.sleep(1)
print("finish!")#It is output together with the above print. .. ..

#If you use flush ...
time.sleep(1)
print("processing B(flush=True)", flush=True)#Will be displayed soon!
time.sleep(1)
print("finish!", flush=True)

Recommended Posts

Immediate display, forced display, flash of print output result with python (mainly jupyter)
UnicodeEncodeError struggle with standard output of python3
Interactively display algebraic curves with Python and Jupyter
Planar skeleton analysis with Python (4) Handling of forced displacement
Basics of python: Output
I wrote the basic grammar of Python with Jupyter Lab
Mass generation of QR code with character display by Python
Try Python output with Haxe 3.2
Try running Python with Try Jupyter
Save the result of the life game as a gif with python
[Understanding / application of with syntax] Flexible switching of Python standard output destination
I want to output the beginning of the next month with Python
Output the contents of ~ .xlsx in the folder to HTML with Python
Real-time display of video acquired from webcam on Jupyter notebook (Python3)