简体   繁体   中英

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 . The add_parser method "takes a command name and any ArgumentParser constructor arguments, and returns an ArgumentParser object that can be modified as usual."

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 ?

I think mgilson's answer is almost correct, but you can do it without relying on implementation details like this:

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. . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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