如何在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
相关产品推荐
相关产品推荐

