I'd like to run the following code in Jupyter notebook:
from time import sleep
print("Something I won't update.")
for i in range(10):
sleep(.5)
print("a%d\nb%d" % (i, i+1), end="\033[A\r")
The targeted result is the following: it prints at time i=0
:
Something I won't update.
a0
b1
Then at time i=1
, the three lines above are replaced by:
Something I won't update.
a1
b2
And so forth and so on...
This works properly in a terminal but not in my notebook where the ANSI escape \033[A
is considered as an empty character ''
. In other words, in Jupyter, I get at time i=0
:
Something I won't update.
a0
b1
And at time i=1
, the output is updated as follows:
Something I won't update.
a0
a1
b2
__EDIT__
Similar questions have been raised on Stack Overflow:
Overwrite previous output in jupyter notebookOverwrite previous output in Jupyter Notebook
How to overwrite the previous print line in Jupyter / IPythonHow to overwrite the previous print line in Jupyter IPython
However, they only cover the cases:
- How to rewrite a single line which can be handled by:
import sys
from time import sleep
print("Something I won't update.")
for i in range(10):
sleep(.5)
sys.stdout.write("\r%d" % i)
This is not working with paragraphs (multiple lines). The behavior is the same than the one described above.
- How to rewrite the whole cell:
from IPython.display import clear_output
from time import sleep
print("Something I won't update.")
for i in range(10):
sleep(.5)
clear_output(wait=True)
print("a%d\nb%d" % (i, i+1))
Here the behavior is not the desired one as the line Something I won't update.
will disappear. In a more practical usecase, I have other things to display like matplotlib figures that I don't want to remove.
The purpose of this question is to be able to rewrite several specific lines. Is there anyway to get the desired behavior in Jupyter ?