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

如何在Bash脚本中调用带参数的Jupyter Notebook函数?

从Bash命令行调用Jupyter Notebook中的带参函数

方法1:直接通过ipython命令执行

你可以在ipython -c指令里先加载Notebook中的代码,紧接着调用目标函数并传入参数,语法如下:

# 传入固定参数
ipython -c "%run another_test.ipynb; find_error(10)"

# 从Bash变量传递参数,比如n=7
n=7
ipython -c "%run another_test.ipynb; find_error($n)"

# 若需要查看函数返回结果,添加print输出
ipython -c "%run another_test.ipynb; print(find_error($n))"

核心逻辑是%run another_test.ipynb会把Notebook内的所有代码(包括find_error函数定义)加载到ipython会话中,之后就能直接调用该函数。

方法2:处理字符串类型参数

如果函数需要传入字符串参数,要在ipython指令里给字符串加单引号,避免Bash解析出错:

str_param="sample_text"
ipython -c "%run another_test.ipynb; find_error('$str_param')"

备选方案:临时转换为Python脚本(复杂场景适配)

如果Notebook包含大量交互式输出影响调用稳定性,可先用nbconvert转成纯Python脚本再调用,用完可删除临时文件:

# 转换ipynb为py文件
jupyter nbconvert --to script another_test.ipynb
# 调用函数
python -c "import another_test; another_test.find_error(5)"
# 删除临时生成的py文件
rm another_test.py

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:27:05