Python 如何正确使用 argparse 子解析器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17073688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:21:53  来源:igfitidea点击:

How to use argparse subparsers correctly?

pythonargparse

提问by user1571144

I've been searching through allot of the subparser examples on here and in general but can't seem to figure this seemingly simple thing out.

我一直在这里和一般情况下搜索分配的子解析器示例,但似乎无法弄清楚这个看似简单的事情。

I have two var types of which one has constraints so thought subparser was the way to go. e.g. -t allows for either "A" or "B". If the user passes "A" then they are further required to also specify if it is either "a1" or "a2". If they pass just "B" then nothing.

我有两种 var 类型,其中一种有约束,所以认为 subparser 是要走的路。例如 -t 允许“A”或“B”。如果用户通过“A”,则他们还需要进一步指定它是“a1”还是“a2”。如果他们只通过“B”,那么什么都没有。

Can I do this and have argparse return me what type of "A" was passed or if it was just "B"?

我可以这样做并让 argparse 返回我传递的是什么类型的“A”还是只是“B”?

The below seems to work but for some reason breaks when passing anything after the subparse.

以下似乎有效,但由于某种原因,在 subparse 之后传递任何内容时会中断。

e.g. from a linux terminal

例如从Linux终端

>> python test01.py -t A a1 -v 61

errors with...

错误...

usage: test01.py a1 [-h]
test01.py a1: error: unrecognized arguments: -v

Hopefully that makes sense.

希望这是有道理的。

The code:

编码:

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='types of A')

parser.add_argument("-t",
                    choices = ["A", "B"],
                    dest = "type",
                    required=True,
                    action='store',
                    help="Some help blah blah")

cam_parser = subparsers.add_parser('a1', help='Default')
cam_parser.set_defaults(which='a1')

cam_parser = subparsers.add_parser('a2', help='parse this instead of default')
cam_parser.set_defaults(which='a2')


parser.add_argument("-v",
                    nargs = '+',
                    required=True,
                    dest = "version",
                    type=int,
                    action='store',
                    help="some version help blah blah")   

argument = parser.parse_args()

print argument.type
print argument.version

采纳答案by chepner

Subparsers are invoked based on the value of the first positionalargument, so your call would look like

根据第一个位置参数的值调用子解析器,因此您的调用看起来像

python test01.py A a1 -v 61

The "A" triggers the appropriate subparser, which would be defined to allow a positional argument and the -voption.

“A”触发适当的子解析器,该子解析器将被定义为允许位置参数和-v选项。

Because argparsedoes not otherwise impose any restrictions on the order in which arguments and options may appear, and there is no simple way to modify what arguments/options mayappear once parsing has begun (something involving custom actions that modify the parser instance might work), you should consider replacing -titself:

因为argparse不会对参数和选项可能出现的顺序施加任何限制,并且没有简单的方法来修改解析开始后可能出现的参数/选项(涉及修改解析器实例的自定义操作可能会起作用),你应该考虑更换-t自己:

import argparse

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='types of A')
parser.add_argument("-v", ...)

a_parser = subparsers.add_parser("A")
b_parser = subparsers.add_parser("B")

a_parser.add_argument("something", choices=['a1', 'a2'])

Since -vis defined for the main parser, it must be specified beforethe argument that specifies which subparser is used for the remaining arguments.

由于-v是为主解析器定义的,因此必须在指定哪个子解析器用于其余参数的参数之前指定。