Reset ipython kernel

2019-02-11 10:56发布

I was wondering if there is a way to restart the ipython kernel without closing it, like the kernel restart function that exists in the notebook. I tried %reset but that doesn't seem to clear the imports.

6条回答
祖国的老花朵
2楼-- · 2019-02-11 11:15

I could restart the kernel, but some console sessions take longer to reconnect. Notebook detects kernel restart instantly.

ipykernel.ipkernel.IPythonKernel class has a do_shutdown method with restart parameter which defaults to False.

Get a reference to ipykernel.kernelapp.IPKernelApp which has a reference to the kernel and call do_shutdown of the kernel by passing True.

import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True)  

How did I test?

$ #start notebook
$ jupyter notebook

$ #connect to existing kernel
$ jupyter console --existing
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-02-11 11:16

In the qt console you could hit ctrl-

查看更多
何必那么认真
4楼-- · 2019-02-11 11:23

Even though it would be handy if %reset would clear the namespace and the cache for the imports (as in the notebook) one can explicitly reload a previously imported module using importlib.reload in python3.4 or imp.reload in python3.0-3.3 (and if needed reset the kernel in a second step).

查看更多
迷人小祖宗
5楼-- · 2019-02-11 11:25

IPython Qt-console has a reset kernel feature. You could use that if you are using IPython Qt. IMO it is better than using from the shell.

enter image description here

查看更多
仙女界的扛把子
6楼-- · 2019-02-11 11:29

If you have installed Spyder with anaconda, then open Spyder window.

Then Consoles (menu bar) -> Restart Consoles.

or you can use CTRL+. which is a shortcut key to restart the console.

查看更多
等我变得足够好
7楼-- · 2019-02-11 11:31

From https://github.com/jupyter/notebook/blob/f19d68a33193dff07e62f11da0ebce331e8acbda/notebook/services/kernels/handlers.py#L75:

class KernelActionHandler(APIHandler):

    @web.authenticated
    @json_errors
    @gen.coroutine
    def post(self, kernel_id, action):
        km = self.kernel_manager
        if action == 'interrupt':
            km.interrupt_kernel(kernel_id)
            self.set_status(204)
        if action == 'restart':

            try:
                yield gen.maybe_future(km.restart_kernel(kernel_id))
            except Exception as e:
                self.log.error("Exception restarting kernel", exc_info=True)
                self.set_status(500)
            else:
                model = km.kernel_model(kernel_id)
                self.write(json.dumps(model))
        self.finish()
查看更多
登录 后发表回答