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
).