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

Python使用argparse接收多个同名命令行参数的实现方法

解决方法

你只需要将add_argument中配置的nargs='+'参数替换为action='append'即可。action='append'的作用就是将每次传入的同名参数的值按顺序追加到列表中,完全适配你需要重复传入--test参数的需求。
另外注意你原代码中choices的每个选项末尾多了多余空格,会导致合法参数匹配失败,需要一并修正。

修改后的完整代码如下:

import argparse

parser = argparse.ArgumentParser(description='Arg Parser',
            formatter_class=argparse.ArgumentDefaultsHelpFormatter,
            allow_abbrev=False)

parser.add_argument('--test', action='append', required=True,
                help='Modules name for sanity check', choices=['test1', 'test2', 'test3'])

parser.add_argument('--config')

arg = parser.parse_args()

修改后即可按照你期望的格式调用:

python3 script.py --test test1 --test test2 --test test3 --config config_path

最终所有传入的--test参数值会按顺序保存在arg.test列表中,结构为['test1', 'test2', 'test3']。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:15:01