Jupyter Notebook中JS变量传Python遇IPython未定义错误求助
解决JupyterLab中
IPython is not defined错误,实现JS变量传递到Python 你遇到的Uncaught ReferenceError: IPython is not defined是因为当前使用的是JupyterLab环境,而IPython.notebook是经典Jupyter Notebook(旧版)的专属全局API对象。JupyterLab重构了前端架构,不再暴露这个全局变量,导致旧代码无法运行。以下是三种可行的解决方法:
方法一:使用JupyterLab原生前端API执行代码
直接调用JupyterLab的前端服务管理器获取内核,执行Python代码:
from IPython.display import HTML HTML(''' <script type="text/javascript"> // 获取JupyterLab应用实例 const app = window.jupyterapp; // 获取默认内核并执行代码 app.serviceManager.kernels.get(app.serviceManager.kernelspecs.default).then(kernel => { kernel.requestExecute({code: "foo=97"}); }); </script> ''')
执行完成后,在Python单元格中输入print(foo)即可验证变量已传递。
方法二:使用ipywidgets传递变量(跨环境推荐)
这种方式同时支持经典Notebook和JupyterLab,是官方推荐的稳定方案:
- 确保ipywidgets已配置(未配置则执行以下命令):
pip install ipywidgets jupyter nbextension enable --py widgetsnbextension jupyter labextension install @jupyter-widgets/jupyterlab-manager
- 在Notebook中运行以下代码:
from ipywidgets import widgets from IPython.display import display, HTML # 创建用于接收JS值的文本组件 input_widget = widgets.Text() display(input_widget) # JS代码将值传入组件并触发Python端感知 HTML(''' <script type="text/javascript"> const inputElem = document.querySelector('.widget-text input'); inputElem.value = "97"; inputElem.dispatchEvent(new Event('input')); </script> ''') # 从组件读取变量到Python foo = int(input_widget.value) print(foo)
方法三:切换到经典Jupyter Notebook环境
如果需要沿用旧代码的写法,直接启动经典Notebook而非JupyterLab即可:
jupyter notebook
启动后运行你原来的代码,IPython.notebook.kernel.execute就能正常工作。
内容的提问来源于stack exchange,提问作者jerik
相关产品推荐
相关产品推荐

