简体   繁体   English

在 jupyter 笔记本上的同一行上打印

[英]Printing on the same line on a jupyter notebook

In python 3, we can easily print on the same line using the following script.在 python 3 中,我们可以使用以下脚本轻松地在同一行上打印。 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)但是,在 jupyter 中它不起作用(它打印在不同的行上)

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.关闭 %pprint 的漂亮打印不起作用,我对 sys.stdout.write() 进行了同样的尝试,但我也遇到了这个问题。

Found the solution to this a bit later (note that it does not work in pycharm jupyter, but only in the browser implementation).稍后找到了解决方案(请注意,它在 pycharm jupyter 中不起作用,而仅在浏览器实现中起作用)。 For me print works fine, but here display is advised, but it prints apostrophes around strings.对我来说, print工作正常,但这里建议display ,但它会在字符串周围打印撇号。

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.编辑:只是想补充一点,TQDM 通常也是实现这一目标的好工具。 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}")

The part "\\r" overwrites the line, if you leave that you append to the line.部分 "\\r" 覆盖该行,如果您保留该部分,则将其附加到该行。 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.你的版本print(f, end='', flush=False)可以工作,但我在 Python 3 下读过你需要使用 sys.stdout.write() 并且最好是如果你也添加flush命令。

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某些系统需要 stdout.flush 否则您将无法获得任何输出

Prefix a \\r and add an argument end="" to print, like so前缀一个\\r并添加一个参数end=""来打印,就像这样

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

This works in the Jupyter notebook in Google Colab.这适用于 Google Colab 中的 Jupyter notebook。

In some cases, the issue could arise when multiple arguments are given to the print statement.在某些情况下,当向打印语句提供多个 arguments 时,可能会出现问题。

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

The above snippet prints 2 - 0 - 1 - 4 in a jupyter notebook.上面的代码片段在 jupyter notebook 中打印2 - 0 - 1 - 4 However, passing a single argument to print will give the desired result of 2 - 4 ie 0 - 0 is overwritten by 1 - 2 which is in-turn overwritten by 2 - 4但是,将单个参数传递给print将给出2 - 4的期望结果,即0 - 0被 1 - 2 覆盖,而1 - 2又被2 - 4覆盖

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

Here are the package versions that I am using.这是我正在使用的 package 版本。

# Name                    Version
notebook                  6.4.12
ipython                   8.4.0
python                    3.8.13
jupyter-client            7.3.4                    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM