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

查看:42
本文介绍了使用 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 设置为 '+'

For example, if nargs is set to '+'

就像 '*' 一样,所有存在的命令行参数都被收集到一个列表中.此外,如果没有在至少存在一个命令行参数.

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天全站免登陆