argparse的参数列表 [英] List of arguments with argparse

查看:91
本文介绍了argparse的参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用argparse传递参数列表,但是我发现的唯一方法是为我要传递的每个参数重写选项:

I'm trying to pass a list of arguments with argparse but the only way that I've found involves rewriting the option for each argument that I want to pass:

我目前使用的是什么

main.py -t arg1 -a arg2

我想:

main.py -t arg1 arg2 ...

这是我的代码:

parser.add_argument("-t", action='append', dest='table', default=[], help="")

推荐答案

使用 nargs :

ArgumentParser 对象通常与单个命令行关联 论点,只需采取一个动作即可. nargs 关键字参数 将不同数量的命令行参数与单个关联 行动.

ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The nargs keyword argument associates a different number of command-line arguments with a single action.

例如,如果nargs设置为'+'

就像'*'一样,所有存在的命令行参数都被收集到一个列表中. 此外,如果不存在,则会生成一条错误消息. 至少存在一个命令行参数.

Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

所以,您的代码看起来像

So, your code would look like

parser.add_argument('-t', dest='table', help='', nargs='+')

这样,-t参数将自动收集到list中(您不必显式指定 action ).

That way -t arguments will be gathered into list automatically (you don't have to explicitly specify the action).

这篇关于argparse的参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆