47

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
  • 39,200
  • 7
  • 84
  • 86
pebox11
  • 3,377
  • 5
  • 32
  • 57
  • 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

5 Answers5

39

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

import os
os._exit(00)
pebox11
  • 3,377
  • 5
  • 32
  • 57
15
import IPython

IPython.Application.instance().kernel.do_shutdown(True) #automatically restarts kernel
Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
user1348692
  • 177
  • 1
  • 5
  • In ipython 8.1.1. this gives ----> 1 IPython.Application.instance().kernel.do_shutdown(True) AttributeError: 'TerminalIPythonApp' object has no attribute 'kernel' – Simd Mar 24 '22 at 17:28
  • 1
    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
7

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
  • 87
  • 1
  • 1
5

If you are using jupyter, there's also this option:

%reset -f

This is not going to fully restart, just reset all variables, which is sometimes what we want.

Fernando Wittmann
  • 1,991
  • 20
  • 16
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
  • 559
  • 1
  • 6
  • 24
  • `print(chr(12))` just prints a control character called "form feed", which is unicode 0x000C (12). It doesn't do anything else. – Noah Wiggin Jul 02 '23 at 05:24