Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPython/ Jupyter notebook clear only one line of output

How can I print the status of a Jupyter notebook on the previous line? I think I'm looking for something like clear_output(), but for only a single line.

Sample code:

from IPython.display import clear_output
import time
print('This is important info!')
for i in range(100):
    print('Processing BIG data file {}'.format(i))
    time.sleep(0.1)
    clear_output(wait=True)
    if i == 50:
        print('Something bad happened on run {}.  This needs to be visible at the end!'.format(i))
print('Done.')

When this runs it gives the behavior of over-writing the previous status line, but both of the lines marked as important (with exclamation points and everything!) are lost. When this is finished the display just says:

Done. 

What it should say is:

This is important info!
Something bad happened on run 50.  This needs to be visible at the end!
Done.

This post suggests using clear_output() and then reprinting everything. This seems impractical because the amount of data I really tend to display is big (lots of graphs, dataframes, ...).

Here's two SO links about clear_output().

Is there a way to make this work that doesn't involve reprinting everything?

like image 276
Casey Avatar asked Mar 29 '18 14:03

Casey


Video Answer


2 Answers

I got it woking using the update function of the display handle:

from IPython.display import display
from time import sleep

print('Test 1')
dh = display('Test2',display_id=True)
sleep(1)
dh.update('Test3')
like image 191
Jan-Philipp Avatar answered Nov 15 '22 08:11

Jan-Philipp


This will do it:

import IPython

IPython.display.display_javascript(r'''
    var el = document.querySelector('.output_text:last-of-type > pre');
    el.innerHTML = el.innerHTML.replace(/(\n.*$)/gm,""); ''', raw=True)
like image 43
Artem Avatar answered Nov 15 '22 09:11

Artem