Ipython laptop does NOT print until the entire program is completed

import time print 1 time.sleep(5) 

I executed the code above in an IPython notebook and a regular script separately.

In IPython Notebook it does not print the number “1” until time.sleep(5) , but in a regular script, it first prints the number “1” and goes to time.sleep(5) . What would happen?

This example just illustrates my problem: I use print to print some text at each stage of my code, which takes a lot of time so that I can know what the program is for. I found this to work fine when running a script, but in IPython Notebook print often lags and everything prints when the whole program is complete.

Is there a way to solve this in an IPython Notebook ?

+7
python printing ipython-notebook progress
source share
1 answer

This is a buffering problem. Add sys.stdout.flush() after printing to see the result right away. You can also use the python -u command or install PYTHONUNBUFFERED envvar. See Disable output buffering .

python uses string buffering if it starts interactively (in the terminal) and blocks buffering (e.g. ~ 4 KB bytes) if the output is redirected. For comparison:

 $ python your_script.py 

and

 $ python your_script.py | cat 

The output is delayed in the second case.

See the second reason in Q: Why not just use pipe (popen ())?

+12
source share

All Articles