Overwrite previous output in jupyter notebook

前端 未结 2 2032
一生所求
一生所求 2020-12-05 17:20

Let\'s assume I have a part of code that runs for some specific amount of time and each 1 second outputs something like this: iteration X, score Y. I will subst

2条回答
  •  北海茫月
    2020-12-05 17:48

    The usual (documented) way to do what you describe (that only works with Python 3) is:

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

    In Python 2 we have to sys.stdout.flush() after the print, as it shows in this answer:

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

    Using IPython notebook I had to concatenate the string to make it 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='')
    

    Or you could split the prints before and after the time.sleep if it makes more 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='')
    

提交回复
热议问题