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

如何将Jupyter Notebook作为可传参的Python函数调用?

如何像调用普通函数一样执行Jupyter Notebook并传递参数

方案一:使用papermill(推荐,简洁高效)

papermill是专门为参数化运行Notebook设计的工具,完全匹配你的复用需求。

1. 安装依赖

pip install papermill

2. 改造目标Notebook

在graph_parser.ipynb中添加一个标记为parameters的单元格(在Jupyter的单元格属性面板设置标签),用于接收外部参数:

# 单元格标签设为parameters
input_file_path = ""  # papermill会自动替换这个值

在Notebook处理逻辑的末尾,将最终结果赋值给一个明确的变量:

# 假设这是你的图解析逻辑生成的结果对象
result_graph = parse_graph(input_file_path)

3. 编写调用函数

直接用papermill的API执行Notebook、注入参数并提取结果:

import papermill as pm

def run_notebook(notebook_path, input_file):
    # 临时输出执行后的Notebook(可选,不需要可设为None)
    temp_output_nb = "./temp_executed.ipynb"
    # 执行Notebook并注入参数
    executed_nb = pm.execute_notebook(
        notebook_path,
        temp_output_nb,
        parameters={"input_file_path": input_file}
    )
    # 从执行后的Notebook中提取结果变量
    return executed_nb.namespace['result_graph']

调用方式完全符合你的预期:

notebook_result = run_notebook("local/path/to/graph_parser.ipynb", r".\location\big_graph.txt")

方案二:基于nbconvert API自定义实现(无额外依赖)

如果不想引入第三方库,可以基于nbconvert的原生API实现参数传递和结果提取。

1. 改造目标Notebook

在Notebook开头添加参数接收逻辑,通过环境变量获取外部传入的值:

import os

# 优先读取环境变量中的参数,默认值为空字符串
input_file_path = os.environ.get('NOTEBOOK_INPUT_PATH', "")

同样在Notebook末尾将结果存入全局变量:

result_graph = parse_graph(input_file_path)

2. 编写调用函数

利用ExecutePreprocessor执行Notebook,注入参数后提取结果:

import os
from nbconvert.preprocessors import ExecutePreprocessor
from nbformat import read

def run_notebook(notebook_path, input_file):
    # 通过环境变量传递参数
    os.environ['NOTEBOOK_INPUT_PATH'] = input_file
    
    # 读取目标Notebook
    with open(notebook_path, 'r', encoding='utf-8') as f:
        nb = read(f, as_version=4)
    
    # 执行Notebook(设置超时时间和对应kernel)
    ep = ExecutePreprocessor(timeout=600, kernel_name='python3')
    ep.preprocess(nb, {'metadata': {'path': os.path.dirname(notebook_path)}})
    
    # 从执行后的Notebook命名空间中提取结果
    result = None
    for cell in nb.cells:
        if hasattr(cell, 'execution_count') and cell.execution_count is not None:
            # 遍历单元格的执行命名空间,找到目标结果变量
            if 'result_graph' in cell.metadata.get('variables', {}):
                result = cell.metadata['variables']['result_graph']
                break
    
    # 清理环境变量
    del os.environ['NOTEBOOK_INPUT_PATH']
    return result

调用方式一致:

notebook_result = run_notebook("local/path/to/graph_parser.ipynb", r".\location\big_graph.txt")

注意事项

  • 确保脚本运行环境与Notebook使用的kernel依赖一致,避免包版本冲突
  • 如果结果是复杂自定义对象,建议在Notebook中将其序列化为JSON或pickle,再在调用脚本中反序列化,避免直接eval带来的安全风险
  • papermill方案更成熟,支持多参数类型、结果持久化等特性,更适合生产环境

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:42:28