如何基于依赖列表循环运行Python脚本并传入名称与版本参数
问题描述
我有一个Python脚本example.py,该脚本运行结束时会生成如下格式的依赖列表:
[{'name': 'spew', 'version': 'v1.1.0'} {'name': 'jpath', 'version': 'v0.4.0'} {'name': 'xddf', 'version': 'v1.5.1'}]
我想基于此列表循环运行该脚本,将列表中每个元素的name和version作为输入参数传入。目前我尝试使用subprocess调用,代码如下:
for i in dependencyList: print(i) subprocess.call(['python3', 'path of the script', '--user', '--password', '--another-user', '--another-token'])
但尚未正确传入对应参数,需解决该问题。
解决方案
1. 先修复依赖列表的格式问题
你拿到的依赖列表字符串中,字典之间缺少逗号,无法直接转为可遍历的Python列表,需要先处理成合法结构:
# 假设原始输出是字符串,先做格式修正 raw_deps = """[{'name': 'spew', 'version': 'v1.1.0'} {'name': 'jpath', 'version': 'v0.4.0'} {'name': 'xddf', 'version': 'v1.5.1'}]""" # 把换行替换为逗号,再修正开头可能出现的多余逗号 fixed_deps = raw_deps.replace("\n", ",") if fixed_deps.startswith("[,{"): fixed_deps = fixed_deps.replace("[,{","[{", 1) # 转为Python列表 dependencyList = eval(fixed_deps)
2. 在subprocess调用中传入name和version参数
假设example.py通过--name和--version参数接收对应值,修改subprocess的命令列表,加入这两个参数:
import subprocess for dep in dependencyList: print(f"Processing {dep['name']}@{dep['version']}") subprocess.call([ 'python3', '/实际路径/example.py', # 替换为脚本的真实路径 '--user', '你的用户名', # 替换为实际用户值 '--password', '你的密码', # 替换为实际密码值 '--another-user', '其他用户名', # 替换为实际值 '--another-token', '其他令牌',# 替换为实际值 '--name', dep['name'], # 传入当前依赖的名称 '--version', dep['version'] # 传入当前依赖的版本 ])
关键注意点
- 确保
example.py中已经通过argparse等工具定义了--name和--version的参数接收逻辑,否则脚本无法识别传入的值。 - 如果脚本使用的参数名不是
--name和--version,直接替换为脚本实际要求的参数标识即可。
内容的提问来源于stack exchange,提问作者Demo Demo
相关产品推荐
相关产品推荐

