Этот код выполняет то, что вы описали как альтернативный вариант, с добавлением сохранения контрольной точки перед перезагрузкой, чтобы выходные данные оставались очищенными:
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()
Если вы предпочитаете первый вариант (без перезагрузки страницы,вместо этого сосредоточив внимание на следующей ячейке), просто удалите строки для сохранения контрольной точки и перезагрузки и используйте функцию IPython.display.clear_output()
после части 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 <script>
как код JavaScript, а не в Python.