且构网

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

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

更新时间:2023-12-04 11:39:46

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