在 jupyter 笔记本上的同一行打印 [英] Printing on the same line on a jupyter notebook

查看:66
本文介绍了在 jupyter 笔记本上的同一行打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python 3 中,我们可以使用以下脚本轻松地在同一行上打印.我用它来了解我的循环的进度(还剩多少时间).但是,在 jupyter 中它不起作用(它在不同的行上打印)

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='
', flush=True)
    time.sleep(10)

关闭 %pprint 的漂亮打印不起作用,我用 sys.stdout.write() 尝试了同样的方法,但我也遇到了这个问题.

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.

推荐答案

稍后找到了解决方案(注意它在 pycharm jupyter 中不起作用,而只能在浏览器实现中起作用).对我来说 print 工作正常,但 这里 <建议使用 code>display,但它会在字符串周围打印撇号.

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)

只是想补充一点,TQDM 通常也是实现此目标的好工具.它显示进度条,并允许您在其下方写入输出或对每个进度条进行不同的描述.另请参阅这篇文章.

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}")

这篇关于在 jupyter 笔记本上的同一行打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆