且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-04 11:52:58

稍后找到了解决方案(注意它在 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}")