Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing on the same line on a jupyter notebook

In python 3, we can easily print on the same line using the following script. I use this to understand the progress of my loop (how much time will be left). However, in jupyter it doesnt work (it prints on different lines)

import time for f in range(10):     print(f, end='\r', flush=True)     time.sleep(10) 

It doesnt work to turn pretty print off %pprint, and I tried the same with sys.stdout.write() but also there I have this issue.

like image 339
Roelant Avatar asked Mar 17 '17 11:03

Roelant


People also ask

How do I print text on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")

How do I print multiple lines in a Jupyter notebook?

Luckily, there's a Jupyter setting that you can change to print multiple outputs. The ast_node_interactivity setting allows you to choose which results are shown as outputs. By setting it to 'all', every assign and expression will be shown.

Can you run a single line in Jupyter notebook?

6 - You may have to restart JupyterLab, but now you can easily run a single line or selection of lines with your desired shortcut. Your preferred approach will depend on the nature of the output of the lines in question.


2 Answers

Found the solution to this a bit later (note that it does not work in pycharm jupyter, but only in the browser implementation). For me print works fine, but here display is advised, but it prints apostrophes around strings.

from time import sleep from IPython.display import clear_output, display  for f in range(10):     clear_output(wait=True)     print(f)  # use display(f) if you encounter performance issues     sleep(10) 

Edit: Just wanted to add that TQDM is often also a good tool for this goal. It displays progress bars and allows you to write output below it or differ the description of each bar. See also this post.

import sys from tqdm import tqdm from time import sleep  values = range(3) with tqdm(total=len(values), file=sys.stdout) as pbar:     for i in values:         pbar.set_description('processed: %d' % (1 + i))         pbar.update(1)         sleep(1) 

And the notebook one with nice colours

from tqdm import tqdm, tqdm_notebook from time import sleep  for i in tqdm_notebook(range(2), desc='1st loop'):     sleep(0.01)     tqdm.write(f"Done task {i}") 
like image 144
Roelant Avatar answered Oct 01 '22 11:10

Roelant


Prefix a \r and add an argument end="" to print, like so

print("\rThis will be printed on the same line", end="")

This works in the Jupyter notebook in Google Colab.

like image 25
myopenid Avatar answered Oct 01 '22 11:10

myopenid