Overwrite previous output on jupyter laptop

Suppose I have a piece of code that runs for a certain amount of time, and every 1 second outputs something like this: iteration X, score Y I will replace this function with my black box function:

 from random import uniform import time def black_box(): i = 1 while True: print 'Iteration', i, 'Score:', uniform(0, 1) time.sleep(1) i += 1 

Now, when I run it in a Jupyter notebook , it prints a new line after every second:

 Iteration 1 Score: 0.664167449844 Iteration 2 Score: 0.514757592404 ... 

Yes, after the result becomes too large, the html will become scrollable, but the fact is that I do not need any of these lines except the last. So instead of n lines after n seconds, I want to have only line 1 (last).

I did not find anything like this in the documentation or looked through the magic. A question with almost the same name, but not significant.

+5
source share
2 answers

The usual (documented) way to do what you are describing (which only works with Python 3):

 print('Iteration', i, 'Score:', uniform(0, 1), end='\r') 

In Python 2, we need sys.stdout.flush() after printing, as shown in this:

 print('Iteration', i, 'Score:', uniform(0, 1), end='\r') sys.stdout.flush() 

Using an IPython laptop, I had to concatenate the string for it to work:

 print('Iteration ' + str(i) + ', Score: ' + str(uniform(0, 1)), end='\r') 

And finally, to make it work with Jupyter, I used this:

 print('\r', 'Iteration', i, 'Score:', uniform(0, 1), end='') 

Either you can split print before and after time.sleep if that makes sense, or you need to be more explicit:

 print('Iteration', i, 'Score:', uniform(0, 1), end='') time.sleep(1) print('', end='\r') # or even print('\r', end='') 
+5
source

@cel is right: ipython memory cell output in code

Using clear_output () gives, however, your laptop has some inconvenience. I also recommend using the display () function like this (Python 2.7):

 from random import uniform import time from IPython.display import display, clear_output def black_box(): i = 1 while True: clear_output() display('Iteration '+str(i)+' Score: '+str(uniform(0, 1))) time.sleep(1) i += 1 
+5
source

All Articles