Sunday, 10 November 2019

How to reload a jupyter notebook after a kernel restart?

In a jupyter notebook I would like to define a function in python, which, when called, does the following:

  • Gives out an alert to the user
  • Restarts the notebook kernel
  • Marks the executed cell as done (i.e. without a star, [ ])
  • Focus is on the next cell

Or as an alternative:

  • Gives out an alert to the user
  • Restarts the notebook kernel
  • Clears all the output of the entire notebook
  • Focus is on the first cell again (like a F5 reload of the browser tab).

I have tried the following code

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

but it gives an error

AttributeError: 'function' object has no attribute 'clear_output'

despite this documentation.

When I remove the line

IPython.display.clear_output();

then the kernel is restarted, but I get 2(!) alerts and it looks like that the execution of the next cell is performed. Also, the cells are not cleared , the current cell still does have the star in the brackets ([*]).

How to do it correctly?



from How to reload a jupyter notebook after a kernel restart?

No comments:

Post a Comment