You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python代码中嵌入Jupyter Notebook并访问调用者环境

需求说明

我在代码开发时,希望直接在代码运行的环境中开展工作。之前是通过设置PYTHONBREAKPOINT调用IPython.terminal.embed.InteractiveShellEmbed()来嵌入IPython解释器实现的。现在想改用Jupyter Notebook,这样调试过程可以保存为Notebook,方便后续整理成最终代码。

示例代码如下:

class Myobj(object):
    def __init__(self,arg1,arg2):
        self.a1 = arg1
        self.a2 = arg2
    def doSomething(self):
        breakpoint()

test = Myobj(2,3)
test.doSomething()

触发断点后,我希望能在Jupyter Notebook中访问到self.a1这类当前环境的变量。

我尝试过直接启动Notebook服务器,但之前定义的全局变量无法传入新创建的Notebook内核:

j = 1
t = 'test string'
from notebook.notebookapp import NotebookApp
app = NotebookApp()
app.initialize(["--port", "8888"])
app.start()
解决方案

要实现将当前运行环境嵌入Jupyter Notebook,核心是让Notebook内核连接到当前Python进程,而非启动全新进程。以下是两种可行方法:

方法1:在断点处嵌入当前环境并启动Notebook

修改断点逻辑,在触发时后台启动Notebook服务器,同时将当前进程作为内核嵌入:

from ipykernel.embed import embed
from notebook.notebookapp import NotebookApp
import threading

def start_notebook_server():
    app = NotebookApp()
    app.initialize(["--port", "8888"])
    app.start()

class Myobj(object):
    def __init__(self,arg1,arg2):
        self.a1 = arg1
        self.a2 = arg2
    def doSomething(self):
        # 后台线程启动Notebook,避免阻塞当前进程
        threading.Thread(target=start_notebook_server, daemon=True).start()
        # 嵌入当前环境到IPython内核
        embed()

test = Myobj(2,3)
test.doSomething()

运行后,Notebook服务器启动,新创建的Notebook单元格可直接访问self.a1、test等当前环境的变量。

方法2:自定义全局断点函数

设置PYTHONBREAKPOINT为自定义函数,实现断点触发时自动启动Notebook并绑定当前环境:

import sys
from ipykernel.embed import embed
from notebook.notebookapp import NotebookApp
import threading

def jupyter_breakpoint():
    def run_notebook():
        app = NotebookApp()
        app.initialize(["--port", "8889"])
        app.start()
    # 后台启动Notebook服务器
    threading.Thread(target=run_notebook, daemon=True).start()
    # 嵌入当前运行环境
    embed()

# 替换默认断点钩子
sys.breakpointhook = jupyter_breakpoint

class Myobj(object):
    def __init__(self,arg1,arg2):
        self.a1 = arg1
        self.a2 = arg2
    def doSomething(self):
        breakpoint()

j = 1
t = 'test string'
test = Myobj(2,3)
test.doSomething()

此后每次调用breakpoint(),都会启动Notebook并允许你在当前环境中调试,全局变量j、t和实例变量self.a1均可直接访问。

注意事项

  • 确保已安装依赖包:pip install ipykernel notebook
  • 可通过指定不同端口避免多个Notebook服务器的端口冲突
  • 使用后台线程启动Notebook,防止阻塞当前进程的执行流程

内容的提问来源于stack exchange,提问作者bht

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 10:45:19