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

如何在Jupyter Notebook中多次带不同参数运行Shell脚本

在Jupyter Notebook中用Python循环调用Bash脚本

下面提供几种实用方案,满足你用Python参数列表循环执行Bash脚本的需求:

方法1:使用Python subprocess 模块(推荐)

完全在Python环境中控制循环,灵活度最高,无需依赖魔法命令。

import subprocess

parameter_list = ["arg1", "arg2", "argn"]
for arg in parameter_list:
    # 调用目标Bash脚本,可捕获输出与返回状态
    run_result = subprocess.run(
        ["bash", "shell_script.sh", arg],
        capture_output=True,
        text=True
    )
    # 打印当前参数的执行结果
    print(f"=== 参数 {arg} 执行结果 ===")
    print(run_result.stdout)
    # 若有错误输出则打印
    if run_result.stderr:
        print("错误输出:")
        print(run_result.stderr)
  • subprocess.run() 是Python 3.5+官方推荐的子进程调用方式
  • capture_output=True 可捕获脚本的标准输出和错误输出
  • text=True 将输出转为字符串格式,便于后续处理

方法2:结合IPython魔法命令API

如果习惯用魔法命令,可通过Python代码直接调用%bash魔法命令实现循环。

parameter_list = ["arg1", "arg2", "argn"]
for arg in parameter_list:
    # 动态传递Python变量到Bash命令中
    get_ipython().run_line_magic('bash', f'shell_script.sh {arg}')
  • get_ipython() 用于调用IPython的底层API,直接执行行魔法命令
  • 通过f-string将当前参数拼接进Bash命令,实现逐个执行

方法3:生成临时Bash脚本批量执行

当参数数量较多时,可先生成包含所有执行命令的临时脚本,再一次性运行。

parameter_list = ["arg1", "arg2", "argn"]

# 拼接所有执行命令
batch_script = "\n".join([f"./shell_script.sh {arg}" for arg in parameter_list])

# 写入临时文件
with open("temp_batch_run.sh", "w") as f:
    f.write(batch_script)

# 赋予执行权限并运行
!chmod +x temp_batch_run.sh
!./temp_batch_run.sh

# 可选:执行完删除临时文件
# !rm temp_batch_run.sh
  • 先将所有执行逻辑整合为一个Bash脚本内容
  • 写入临时文件后赋予执行权限,通过!行魔法命令运行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 03:12:47