问题描述
我想为我的程序提供一个参数,该参数包含一些必需的参数以及一些可选的参数.像这样:
I'd like to have an argument to my program that has some required parameters along with some optional parameters. Something like this:
[--print text [color [size]]
因此您可以通过以下任何一种方式:
so you could pass it any of these:
mycommand --print hello
mycommand --print hello blue
mycommand --print hello red 12
可能有多个,因此必须是一个add_argument.例如:
There could be multiple of these so it has to be a single add_argument. For example:
[--print text [color]] [--output filename [overwrite]]
我可以实现接近我想要的参数:
I can achieve arguments that are close to what I want:
>>> parser = argparse.ArgumentParser()
>>> act = parser.add_argument('--foo', nargs=3, metavar=('x','y','z'))
>>> act = parser.add_argument('--bar', nargs='?')
>>> act = parser.add_argument('--baz', nargs='*')
>>> parser.print_help()
usage: [-h] [--foo x y z] [--bar [BAR]] [--baz [BAZ [BAZ ...]]]
optional arguments:
-h, --help show this help message and exit
--foo x y z
--bar [BAR]
--baz [BAZ [BAZ ...]]
但不完全是.有什么办法可以用argparse做到这一点?我知道我可以将它们全部设置为nargs="*"
,但是--help不会列出可选参数的名称.如果我通过nargs="*"
和metavar的元组,则argparse会引发异常.
but not quite. Is there any way to do this with argparse? I know I could make them all nargs="*"
but then --help would not list the names of the optional arguments. If I pass nargs="*"
and a tuple for metavar, argparse throws an exception.
推荐答案
阅读源代码(从take_action
开始),我相信您想要的是不可能的.所有参数解析和传递到操作均基于nargs完成,并且nargs是一个数字,OPTIONAL
(?"),ZERO_OR_MORE
("*"),ONE_OR_MORE
("+"),PARSER
或REMAINDER
.必须在Action对象(处理输入)甚至看到它得到的东西之前确定它,因此它不能动态地找出nargs
.
Reading the source code (start in take_action
), I believe what you want is impossible. All argument parsing and passing to actions is done based on nargs, and nargs is either a number, OPTIONAL
("?"), ZERO_OR_MORE
("*"), ONE_OR_MORE
("+"), PARSER
, or REMAINDER
. This must be determined before the Action object (which handles the input) even sees what it's getting, so it can't dynamically figure out nargs
.
我认为您将需要一个变通方法.我可能会有--foo-x x
,--foo-y y
和--foo-z z
,也许还有--foo x y z
.
I think you'll need to live with a workaround. I would maybe have --foo-x x
, --foo-y y
, and --foo-z z
, and perhaps also --foo x y z
.
这篇关于Python argparse可选子参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!