首页 > 解决方案 > 如何在 Python Jupyter Notebook 的按钮中编写“重新启动内核并运行所有”代码?

问题描述

我正在尝试使用 python 在 Jupyter notebook 中创建一个 GUI。我已经编写了按钮以使用小部件执行代码。但是我遇到了两个问题:

  1. 编写代码片段以重新启动内核并运行所有单元(下面代码片段中的 rs_button)
  2. 不太重要:无论如何我可以隐藏python中的所有代码,只保留按钮以及用户输入单元格显示?

这是我一直在尝试的:

import ipywidgets as widgets
from IPython.display import display
rs_button = widgets.Button(description="Restart Kernel!")
exec_button = widgets.Button(description="Click Me!")
display(rs_button,exec_button)

def rs_button_clicked(b):
    IPython.notebook.execute_cell();


def exec_button_clicked(b):
    import data_assess_v6 as data_profiler
    (execution_time) = data_profiler.data_profile(path,file)

rs_button.on_click(rs_button_clicked)
exec_button.on_click(exec_button_clicked)

谢谢

标签: pythonwidgetjupyter-notebook

解决方案


我已经能够通过将javascript注入笔记本来实现这两个功能。下面是代码片段。

from IPython.display import HTML, Javascript, display

def initialize():
    display(HTML(
        '''
            <script>
                code_show = false;
                function restart_run_all(){
                    IPython.notebook.kernel.restart();
                    setTimeout(function(){
                        IPython.notebook.execute_all_cells();
                    }, 10000)
                }
                function code_toggle() {
                    if (code_show) {
                        $('div.input').hide(200);
                    } else {
                        $('div.input').show(200);
                    }
                    code_show = !code_show
                }
            </script>
            <button onclick="code_toggle()">Click to toggle</button>
            <button onclick="restart_run_all()">Click to Restart and Run all Cells</button>
        '''
    ))
initialize()

restart_run_all()函数重新启动笔记本内核,然后在 10 秒后执行所有单元。可以根据需要调整超时功能的参数。

code_toggle()函数切换笔记本中单元格的输入区域。它还在切换代码单元时提供了一个很好的动画。


推荐阅读