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

如何在for循环中执行Python脚本并传入迭代变量作为命令行参数

解决方案

分两种常见场景处理:

场景1:当前代码是Python脚本(你要在Python代码内循环调用外部process.py)

你原来的写法错误是因为直接写的python process.py ...不是可执行的Python调用逻辑,且没有做变量插值,你可以用subprocess模块实现需求,注意os.listdir()仅返回目录/文件名,需要和父路径拼接得到完整路径:

import os
import subprocess

input_dir_parent = '/home/.../parent_folder/'
for filename in os.listdir(input_dir_parent):
    input_directory = os.path.join(input_dir_parent, filename)
    # 过滤只处理目录(可选,根据你的需求调整)
    if not os.path.isdir(input_directory):
        continue
    # 推荐用列表形式传参,避免目录名带空格等特殊字符时解析出错
    subprocess.run([
        "python", "process.py",
        "--input_dir", input_directory
    ], check=True)

如果要拼接命令字符串的话也可以用f-string实现变量插值:

cmd = f"python process.py --input_dir {input_directory}"
subprocess.run(cmd, shell=True, check=True)

场景2:你本来是想写Shell脚本(代码是写在.sh文件中执行)

你原来的写法混用了Python语法,且Shell中引用变量需要加$前缀,正确写法如下:

input_dir_parent='/home/.../parent_folder/'
# 遍历父目录下的所有子目录
for input_directory in "$input_dir_parent"/*/; do
    python process.py --input_dir "$input_directory"
done

如果要遍历所有文件和目录,把/*/改成/*即可,变量两边加双引号可以避免目录名含空格时的解析错误。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 18:48:02