Printing on the same line on a jupyter notebook

Question:

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.

Asked By: Roelant

||

Answers:

The part “r” overwrites the line, if you leave that you append to the line. Your version print(f, end='', flush=False) could work but I’ve read under Python 3 you need to use sys.stdout.write() and best is if you add flush command too.

import sys
import time

for f in range(10):
    #delete "r" to append instead of overwrite
    sys.stdout.write("r" + str(f))
    sys.stdout.flush()
    time.sleep(10)

The stdout.flush is required on some systems or you won’t get any output

Answered By: CodingYourLife

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}")
Answered By: 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.

Answered By: myopenid

In some cases, the issue could arise when multiple arguments are given to the print statement.

for i in range(3):
    print(i, "-", i ** 2, end="r")

The above snippet prints 2 - 0 - 1 - 4 in a jupyter notebook. However, passing a single argument to print will give the desired result of 2 - 4 i.e. 0 - 0 is overwritten by 1 - 2 which is in-turn overwritten by 2 - 4

for i in range(3):
    print(f"{i} - {i ** 2}", end="r")

Here are the package versions that I am using.

# Name                    Version
notebook                  6.4.12
ipython                   8.4.0
python                    3.8.13
jupyter-client            7.3.4                    
Answered By: Saurabh Parikh
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.