首页 > 解决方案 > 通过 jupyter_client API 优雅地中断 jupyter 内核

问题描述

jupyter qtconsole我的目标是使用API连接到运行jupyter_client并在该内核上远程执行命令。代码的执行工作,但似乎不可能使用Ctrl-C(在qtconsoleconsole)从内核前端中断正在运行的代码。在我的示例代码下面,我在不同的实例中执行qtconsole并且不能被中断:

import jupyter_client as jc

# Find last accessed connection file
cfile = jc.find_connection_file()
km = jc.KernelManager()
km.load_connection_file(connection_file=cfile)
kc.start_channels()

msg = """
import time
for k in range(10):
    print(k)
    time.sleep(1)
"""
kc.execute(msg)


我发现中断执行的唯一方法是直接发送一个SIGINIT,例如通过在另一个jupyter实例中运行以下命令:

import os
import signal

# pid is process identifier of jupyter kernel that runs the loop
os.kill(pid, signal.SIGINT)

问题:有没有更优雅的方式使用jupyter_clientAPI(例如KernelClientKernelManager)中断正在运行的内核?

PS:github 上还有一个 open issue提到了这个问题,但是 jupyter 开发人员到目前为止还不是很敏感。

标签: pythonipythonjupyterjupyter-console

解决方案


推荐阅读