iPython / Jupyter笔记本仅清除一行输出

时间:2018-03-29 14:31:22

标签: python-3.x jupyter-notebook

如何在上一行打印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.

This post建议使用clear_output()然后重新打印所有内容。这似乎不切实际,因为我真正倾向于显示的数据量很大(很多图形,数据帧,......)。

以下是关于clear_output()的two SO个链接。

有没有办法让这项工作不涉及重印一切?

3 个答案:

答案 0 :(得分:0)

这可以做到:

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)

答案 1 :(得分:0)

我使用显示手柄的更新功能将其唤醒:

from IPython.display import display
from time import sleep

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

答案 2 :(得分:0)

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

\r: (Carriage Return) (CR)将光标返回到新行的开头,而不移动到新行。
\n:(Line Feed) (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.')
相关问题