Skip to content Skip to sidebar Skip to footer

Argparse Optional Arguments With Multilevel Parser/subparser

I have a set of parsers and subparsers to build a production or development system. If the user picks production, he can add options and all is well. If he pics development, he can

Solution 1:

aparser.add_argument(...) creates an Action class object, actually a subclass specified by the action parameter. That action/argument may be positional or optional (flagged).

sp=aparse.add_subparsers(...) is specialized version of add_argument that creates an Action of the subparser class. print(sp) will show some of its attributes. This is actually a positional argument, with a choices attribute.

p1 = sp.add_parser(...) creates an argparse.ArgumentParser() object, and links it to a name that is placed in the sp.choices list. The parser is returned as the p1 variable.

p1.add_argument(...) defines a Action/argument, just as done with the main parser.

So during parsing, the inputs (sys.argv) are handled one by one, as is usual. But when it hits a string that matches in position and name of a "p1", the parsing task is passed on to p1 (with what remains of the sys.argv list). When p1 has reached the end of sys.argv its namespace and control is passed to the parent parser. The parent doesn't do any further parsing.

In your case you can pass down through several levels of parsers. (the terms, parser and subparsers can be a bit confusing, at least in the description. They are clearly defined in the code.)

This subparser mechanism allows only one choice (at each level). This isn't a multilevel tree transversal tool. You go down one particular thread to end, and back up.

So with

./buildServer.py Dev arch -arm build -comms or ./buildServer.py Dev arch -arm build -server -tcp

main_parser   (sees 'Dev', passes control to:)
    dev_parser   (sees 'arch', passes control to:)
        action_arch_parser
            (sees -arm - sets the const)
            (doesn't have any positional to handle 'build'
                  returns with an unrechognized arguments)

There may be ways of working around this - I or others have suggested things like this in previous SO - but the straight forward argparse usage does not allow for multiple subparsers (just the nesting that you show).

Post a Comment for "Argparse Optional Arguments With Multilevel Parser/subparser"