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

在ipywidget中调用dbutils.notebook.run运行Azure Databricks笔记本报错

解决Databricks ipywidget中调用dbutils.notebook.run的上下文错误

问题重现

在ipywidgets按钮点击事件中调用dbutils.notebook.run时触发以下错误:

IllegalArgumentException: Context not valid. If you are calling this outside the main thread, you must set the Notebook context via dbutils.notebook.setContext(ctx), where ctx is a value retrieved from the main thread (and the same cell)

直接在单元格执行dbutils.notebook.run("/mynotebook", 60)或使用%run命令均正常,但在ipywidget回调中失效。

解决方案

错误原因是ipywidget的回调函数运行在非主线程,而dbutils.notebook.run依赖主线程的上下文。只需在主线程提前获取上下文,再在回调中注入即可:

修改后的代码

import ipywidgets as widgets
from ipywidgets import Box

# 主线程中提前获取notebook上下文
ctx = dbutils.notebook.getContext()

button = widgets.Button(description='Run model')
out = widgets.Output()

def on_button_clicked(b):
    button.description = 'Running...'
    with out:
        # 先注入上下文,再执行run方法
        dbutils.notebook.setContext(ctx)
        dbutils.notebook.run("/mynotebookpath", 60)
    button.description = 'Run model'

button.on_click(on_button_clicked)
widgets.VBox([button, out])

关键说明

  • dbutils.notebook.getContext()必须在单元格顶级代码(主线程)中调用,不能放在回调函数内
  • 回调执行时先通过setContext注入上下文,确保run方法能识别当前notebook环境
  • 新增按钮状态切换(Running.../Run model),优化交互反馈

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 09:47:16