I want to print some debug statements during a loop in my function and I use IPython to call the function. Let an example function be:
def test_print():
import time
for i in range(5):
time.sleep(2)
print i, time.time()
The result is like follows:
0 1372337149.84
1 1372337151.84
2 1372337153.85
3 1372337155.85
4 1372337157.85
I expect each row to be printed, then wait for 2 seconds. But the behavior is as follows. I first observe:
0 1372337149.84
1
Then, after 2 seconds I observe the time stamp of 1
and the id of the next row, which is 2
. I observe the last time stamp finally. I couldn't figure out why it behaves like this instead of one row at a time. Any thoughts? Do I need a special flush function to print what is waiting to be printed?
Press 'control-shift-p', that opens the command palette. Then type 'clear cell output'. That will let you select the command to clear the output.
What is Clear_output () in Python? clear_output()` in a thread does not block until the output is cleared · Issue #3260 · jupyter-widgets/ipywidgets · GitHub.27-Aug-2021.
Summary: The most straightforward way to overwrite the previous print to stdout is to set the carriage return ( '\r' ) character within the print statement as print(string, end = "\r") . This returns the next stdout line to the beginning of the line without proceeding to the next line.
I've never used IPython, but it should suffice to flush stdout after each print
statement.
Something like this ought to work...
def test_print():
import time
import sys
for i in range(5):
time.sleep(2)
print i, time.time()
sys.stdout.flush()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With