iPython/Jupyter笔记本如何清除仅输出的一行?

8

如何在上一行打印Jupyter笔记本的状态?我认为我正在寻找类似于clear_output()但仅适用于单行的内容。

示例代码:

from IPython.display import clear_output
import time
print('This is important info!')
for i in range(100):
    print('Processing BIG data file {}'.format(i))
    time.sleep(0.1)
    clear_output(wait=True)
    if i == 50:
        print('Something bad happened on run {}.  This needs to be visible at the end!'.format(i))
print('Done.')

当这段代码运行时,它会覆盖之前的状态行,但是两个被标记为重要的行(包括感叹号和其他所有内容!)都会丢失。当代码完成后,显示器上只会显示:
Done. 

它应该说的是:

这是它应该说的:

This is important info!
Something bad happened on run 50.  This needs to be visible at the end!
Done.

这篇文章建议使用clear_output(),然后重新打印所有内容。但是,这似乎不切实际,因为我要显示的数据量很大(有很多图形、数据框等)。

这里有两个 SO关于clear_output()的链接。

有没有一种方法可以使这个工作不涉及重新打印所有内容呢?

3个回答

8
我已经使用显示句柄的更新函数使其工作:
from IPython.display import display
from time import sleep

print('Test 1')
dh = display('Test2',display_id=True)
sleep(1)
dh.update('Test3')

3

这个简单的转义序列技巧可以大多数情况下完成任务。如果正确使用,\n\r可以做很多事情。

\r:(回车符)(CR)将光标返回到新行的开头而不移动到新行。
\n:(换行符)(LF)将光标移动到下一行。

import time
print('This is important info!')
for i in range(100):
    print("\r"+'Processing BIG data file {}'.format(i),end="")
    time.sleep(0.1)
    if i == 50:
        print("\r"+'Something bad happened on run {}.  This needs to be visible at the end!'.format(i))
print("\r"+'Done.')

这对我很有效。没有任何额外的包开销。非常精简。 - Ishrak

2
这样做就可以了:

最初的回答:

import IPython

IPython.display.display_javascript(r'''
    var el = document.querySelector('.output_text:last-of-type > pre');
    el.innerHTML = el.innerHTML.replace(/(\n.*$)/gm,""); ''', raw=True)

稍微解释一下可能会有所帮助,所以我来为您解释一下:您需要获取笔记本的第一个输出块(pre),并使用正则表达式将其HTML(我们的两行输出)替换为仅匹配第二行输出的内容。您可以在代码中使用IPython类的display.display_javascript方法在必要时发出此命令。 - Redoman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接