简体   繁体   English

如何将ArgumentParser子类指定为argparse子解析器?

[英]How to specify an ArgumentParser subclass as an argparse subparser?

The argparse documentation for subcommands says to add a subparser by calling the add_parser method on the object returned by a call to add_subparsers . 子命令argparse文档说,可以通过对add_parser调用返回的对象调用add_parser方法来添加 add_subparsers The add_parser method "takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual." add_parser方法“采用命令名称和任何ArgumentParser构造函数参数,并返回可以照常修改的ArgumentParser对象。”

Beyond creating a subclass that overrides the add_parser method, is there anyway that I can add a subparser that is itself a subclass of ArgumentParser ? 除了创建覆盖add_parser方法的子类之外,我是否还可以添加一个本身就是ArgumentParser子类的子分析器?

I think mgilson's answer is almost correct, but you can do it without relying on implementation details like this: 我认为mgilson的答案几乎是正确的,但您可以这样做而不必依赖于这样的实现细节:

class Foo(ArgumentParser): pass

parser = ArgumentParser()
subparsers = parser.add_subparsers(parser_class=Foo)
subparser = subparsers.add_parser(...)

After looking at the source, ArgumentParser is a subclass of _ActionsContainer whoich inherits from _SubParsersAction whose __init__ sets a _parser_class attribute. 在查看源代码之后, ArgumentParser_ActionsContainer的子类,whoich继承自_SubParsersAction__init__设置了_parser_class属性。 . This attribute is then used to build the new parser . 然后,此属性用于构建新的解析器

in other words, something like: 换句话说,类似:

class Foo(ArgumentParser): pass

parser = ArgumentParser()
parser._parser_class = Foo
subparser = parser.add_parser(...)

should work (although I haven't tested it). 应该可以工作 (尽管我还没有测试过)。 You'd be relying on an implementation detail here ... but I don't think there's any official way to get it to work. 您可能会在这里依赖于实现细节...但是我认为没有任何正式的方法可以使它起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM