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

查看:592
本文介绍了在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='\r', 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可以正常工作,但建议此处 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天全站免登陆