Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to code "Restart Kernel and Run all" in button for Python Jupyter Notebook?

I'm trying to create a GUI in Jupyter notebook using python. I have coded the buttons to execute the code using widgets. But I'm running into two issues:

  1. Code a snippet to restart kernel and run all cells (rs_button in the code snippet below)
  2. Less important: Is there anyway I can hide all the codes in python and just keep the buttons as well as user input cells on display?

Here's what I've been trying:

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)

Thanks

like image 442
Padma Dwivedi Avatar asked Feb 26 '19 13:02

Padma Dwivedi


1 Answers

I have been able to achieve these 2 functionalities by injecting javascript into the notebook. Below is the code snippet.

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

The restart_run_all() function restarts the notebook kernel and then executes all cells after 10 seconds. The parameter to the timeout function can be adjusted as necessary.

The code_toggle() function toggles the input areas of the cells in the notebook. It also gives a nice animation while toggling the code cells.

like image 63
Suraj Potnuru Avatar answered Oct 13 '22 10:10

Suraj Potnuru