35

Is it possible to restart an ipython Kernel NOT by selecting Kernel > Restart from the notebook GUI, but from executing a command in a notebook cell?

Thomas K
  • 37,597
  • 7
  • 80
  • 84
pebox11
  • 2,777
  • 5
  • 29
  • 46
  • 2
    Not intentionally, but any command which kills the kernel process will cause it to be automatically restarted. I think IPython catches `sys.exit()`, but [os._exit()](https://docs.python.org/3/library/os.html#os._exit) will make it die. This skips all of Python's normal cleanup (e.g. `atexit`), though. If you just want a way to restart the kernel from the keyboard, the shortcut is `00`. – Thomas K Jun 13 '16 at 10:35
  • Thank you very much. Now that is definitely something I will have to check. Thank you! – pebox11 Jun 13 '16 at 11:43

4 Answers4

30

As Thomas K. suggested, here is the way to restart the ipython kernel from your keyboard:

import os
os._exit(00)
pebox11
  • 2,777
  • 5
  • 29
  • 46
10
import IPython

IPython.Application.instance().kernel.do_shutdown(True) #automatically restarts kernel
Jeremy Caney
  • 6,191
  • 35
  • 44
  • 70
user1348692
  • 119
  • 1
  • 5
  • In ipython 8.1.1. this gives ----> 1 IPython.Application.instance().kernel.do_shutdown(True) AttributeError: 'TerminalIPythonApp' object has no attribute 'kernel' – graffe Mar 24 '22 at 17:28
  • In IPython 8 and above, kernel can be accessed via `get_ipython().kernel`, so the above becomes `get_ipython().kernel.do_shutdown()` —`get_ipython` is a global available in Jupyter notebook and Colab but not interactive python shell. – Matteo Ferla May 24 '22 at 11:07
6

To define a function that restarts the Jupyter kernel, I've successfully used:

from IPython.display import display_html
def restartkernel() :
    display_html("<script>Jupyter.notebook.kernel.restart()</script>",raw=True)

then calling

restartkernel()

when time for the restart.

wpressNR
  • 77
  • 1
  • 1
0

Try print(chr(12)).

I am not sure what this function does behind the scenes, but if you are looking for a way to hide all previous outputs (such as in-memory 'card' game), it works.

Roman Sinyakov
  • 522
  • 1
  • 6
  • 23