python 参数解析器定义列表类型输入的变量名

python argument parser defines variable name for list type input

我可以选择读取用户输入的列表。该列表可以具有随机长度。这是我的代码:

parser.add_argument('-at', '--addTests', metavar=('test_commands'), nargs='+')

使用 'metavar' 是给变量命名的好方法,但当 nargs 不固定时,它不会很好地工作。

我从这一行得到的结果是:

-at test_command [test_command ...], --addTests test_command [test_command]

希望结果只有"test_command"显示一次

您对

的含义感到困惑
--addTests test_command [test_command]

你认为这意味着 [test_command] 是一个参数列表。

请注意,[arg] 符号用于可选参数。由于您使用了 nargs='+',因此用户必须为 -at/--addTests 选项至少提供 一个参数,以及任何其他参数对于 --addTests.

是可选的

因此,使用:

--addTests test_command test_command2

调用脚本时:

args = parser.parse_args()

将给出以下经过解析的参数:

Namespace(addTests=['test_command', 'test_command2']

然后您可以使用以下方式访问它们:

for command in args.addTests: 
    print command

或者(而不是打印)您可以 运行 命令等