如何通过代码或算法重新启动内核并重新运行Python Jupyter Notebook中的所有单元格?

时间:2020-07-14 12:59:11

标签: python

需要Python脚本,该脚本将重新启动内核并自动重新运行所有单元,而无需任何人工干预。

我在下面尝试了以下代码,但由于使用了切换按钮,因此需要人工干预。

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()

1 个答案:

答案 0 :(得分:0)

稍微修改一下代码似乎对我有用:

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
                }
                restart_run_all();
            </script>
        '''
    ))

注意:我刚刚删除了按钮并在

之前调用了restart_run_all()函数
相关问题