在jupyter笔记本中,我想在python中定义一个函数,它在调用时执行以下操作:
[ ])或者作为另一种选择:
我尝试了以下代码
from IPython.display import display, HTML
def reload():
display(HTML(
'''
<script>
alert('This notebook needs to be restarted!');
IPython.notebook.kernel.restart();
IPython.display.clear_output();
window.location.reload();
</script>
'''
))
reload()但它给出了一个错误
AttributeError: 'function' object has no attribute 'clear_output'尽管这份文件。
当我移除线时
IPython.display.clear_output();然后重新启动内核,但我得到了2(!)警报,并且看起来下一个单元格的执行将被执行。此外,单元格未被清除,当前单元格中仍然有方括号([*])中的星。
怎样才能做好呢?
发布于 2019-11-12 10:03:27
此代码执行您所描述的替代选项,在重新加载之前添加保存检查点,以便输出保持清除:
from IPython.display import Javascript, display
def reload():
display(
Javascript('''
// clear all output (based on: https://stackoverflow.com/a/47315713/9504155)
// save a reference to the cell we're currently executing inside of,
// to avoid clearing it later (which would remove this js)
var this_cell = $(element).closest('.cell').data('cell');
function clear_other_cells () {
Jupyter.notebook.get_cells().forEach(function (cell) {
if (cell.cell_type === 'code' && cell !== this_cell) {
cell.clear_output();
}
Jupyter.notebook.set_dirty(true);
});
}
if (Jupyter.notebook._fully_loaded) {
// notebook has already been fully loaded, so clear now
clear_other_cells();
}
// save checkpoint so output stays cleared after reload
IPython.notebook.save_checkpoint();
IPython.notebook.kernel.restart();
alert('This notebook needs to be restarted!');
window.location.reload(false);
'''))
reload()如果您更喜欢第一个选项(而不是重新加载页面,而是集中在下一个单元格上),只需删除保存检查点和重新加载的行,并在JavaScript部件之后使用JavaScript函数来清除当前单元格的输出:
from IPython.display import Javascript, clear_output, display
def reload():
display(
Javascript('''
// clear all output (based on: https://stackoverflow.com/a/47315713/9504155)
// save a reference to the cell we're currently executing inside of,
// to avoid clearing it later (which would remove this js)
var this_cell = $(element).closest('.cell').data('cell');
function clear_other_cells () {
Jupyter.notebook.get_cells().forEach(function (cell) {
if (cell.cell_type === 'code' && cell !== this_cell) {
cell.clear_output();
}
Jupyter.notebook.set_dirty(true);
});
}
if (Jupyter.notebook._fully_loaded) {
// notebook has already been fully loaded, so clear now
clear_other_cells();
}
IPython.notebook.kernel.restart();
alert('Notebook output cleared!');
'''))
clear_output()IPython.display.clear_output();没有在您的代码中工作,因为它在HTML标记中被调用为JavaScript代码,而不是在JavaScript中。
发布于 2019-11-05 13:11:20
我不确定您遇到的其他问题,但代码
IPython.display.clear_output();成功地运行在我的jupyter笔记本中没有问题,您确定您的jupyter笔记本版本是最新的还是在文档中相同的版本?不足为奇的是,不同的版本可能有不同的功能名称,甚至整个结构也可能有所不同。
https://stackoverflow.com/questions/58711404
复制相似问题