带有子解析器和可选位置参数的 Python argparse
我想要一个带有子解析器的程序,它可以处理特定的参数,同时保留一些位置和可选参数给前面的解析器(实际上我真正想要的只是一个选项,我的意思是,一个有效的子解析器或一个有效的本地论据).
I would like to have a program with subparsers that handles specific arguments while also keep some positional and optional arguments to the previous parsers (In fact what I really want is only one option, I mean, a valid subparser OR a valid local argument).
我希望拥有的示例:Program [{sectionName [{a,b}]}] [{c,d}]
.如果提供了 sectionName,则 c/d 不兼容,反之亦然.
Example of something I wish to have: Program [{sectionName [{a,b}]}] [{c,d}]
. Being c/d incompatible if sectionName was provided and viceversa.
然而,我能做到的最好的就是这个 test.py [-h] {sectionName} ... [{c,d}]
.这意味着,argparse 不允许我在没有指定有效 sectionName
的情况下使用位置参数 c 或 d.
However, the best I could achieve is this test.py [-h] {sectionName} ... [{c,d}]
. This means, argparse don't allow me to use the positional arguments c or d without specifying a valid sectionName
.
代码如下:
import argparse
mainparser = argparse.ArgumentParser()
# Subparser
subparser = mainparser.add_subparsers(title="section", required=False)
subparser_parser = subparser.add_parser("sectionName")
subparser_parser.add_argument("attribute", choices=['a', 'b'], nargs='?')
# Main parser positional and optional attributes
mainparser.add_argument("attribute", choices=['c', 'd'], nargs='?')
mainparser.parse_args()
我快被这个弄疯了.任何帮助将不胜感激!
I'm getting crazy with this. Any help would be much appreciated!
我正在使用 Python 3.8
subparser
对象实际上是一个位置Action
,它接受choices
- 在这种情况下 {'sectionName'}
.positinal
参数按照定义的顺序填充,使用 nargs
模式分配字符串.
The subparser
object is actually a positional Action
, one that takes choices
- in this case {'sectionName'}
. positinal
arguments are filled in the order that they are defined, using the nargs
pattern to allocate strings.
一旦主解析器获得sectionName",它就会将解析传递给subparser_parser
.Than 处理输入的其余部分,例如 {'a','b'}
位置.它无法处理的任何内容都放在无法识别"列表中,并且控制返回 main
进行最终处理.main
不做任何进一步的参数处理.因此,您的 attribute
参数将被忽略.
Once the main parser gets the 'sectionName' it passes the parsing to subparser_parser
. Than handles the rest of the input, such as the {'a','b'}
positional. Anything it can't handle is put on the 'unrecognized' list, and control returns main
for final processing. main
does not do any further argument processing. Thus your attribute
argument is ignored.
您可以在 add_subparsers
之前定义一个 attribute
位置,但我不会尝试使其成为 nargs='?'
.
You could put define a attribute
positional before the add_subparsers
, but I wouldn't try to make it nargs='?'
.
因此最好在子解析器之前定义所有main
参数,并使用optionals
.这将提供最干净、最可靠的解析.
So it's best to define all main
arguments before the subparsers, and to use optionals
. This will give the cleanest and most reliable parsing.