aress31
aress31

Reputation: 350

Argparse nested subparsers

I would like to created nested subparsers using the python 3 library argparse. At the moment I am getting this error message when trying to implement a solution:

AttributeError: 'ArgumentParser' object has no attribute 'add_parser'

Here is the code that I am using:

def parse_args():
    """
    Parse and validate user command line.
    """
    # Top-level parser
    parser = argparse.ArgumentParser(
        description="foo"
    )

    parser.add_argument(
        "-foo",
        dest="foo",
        help="foo",
        required=True,
        type=str
    )

    subparsers = parser.add_subparsers(help='sub-command help')

    # Parser for the "payload" command
    parser_payload = subparsers.add_parser(
        "payload", 
        help="payload help"
    )

    parser_payload.add_argument(
        "-b",
        "--bar",
        dest="bar",
        help="bar",
        type=str
    )

    # Parser for the "payload->foobar" command
    parser_payload_foobar = parser_payload.add_parser(
        "foobar"
        help="foobar help"
    )

    parser_payload_foobar.add_argument(
        "-bf",
        "--barfoo",
        dest="barfoo",
        help="barfoo",
        type=str
    )

    return parser.parse_args()

Upvotes: 1

Views: 2818

Answers (1)

hpaulj
hpaulj

Reputation: 231365

Do you see a pattern here?

subparsers = parser.add_subparsers(help='sub-command help')
...
parser_payload = subparsers.add_parser(   # ok
...
parser_payload.add_parser(    # error

parser has a add_subparsers method. A subparsers object (what ever that is) has a add_parser method. The error message says that a parser does not have that method.

If you want to add subparsers to parser_payload you have to start with the add_subparsers method.

argparse is organized around classes, whether it's obvious from the documentation or not. Each class has its defined methods.

I like to develop in an interactive environment in which I can examine the class and attributes of the objects as the get created.

Upvotes: 2

Related Questions