通过jupyter_客户端API优雅地中断jupyter内核

2024-10-05 15:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是使用jupyter_clientAPI连接到正在运行的jupyter qtconsole,并在该内核上远程执行命令。代码的执行工作正常,但似乎不可能使用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开发人员到目前为止还没有很好的响应


Tags: 实例代码importjupytermsgconnection内核file