argparse subparser monolithic help output

后端 未结 5 553
予麋鹿
予麋鹿 2020-11-29 06:02

My argparse has only 3 flags (store_true) on the top level, everything else is handled through subparsers. When I run myprog.py --help, the output shows a list

5条回答
  •  星月不相逢
    2020-11-29 06:18

    This is a bit tricky, as argparse does not expose a list of defined sub-parsers directly. But it can be done:

    import argparse
    
    # create the top-level parser
    parser = argparse.ArgumentParser(prog='PROG')
    parser.add_argument('--foo', action='store_true', help='foo help')
    subparsers = parser.add_subparsers(help='sub-command help')
    
    # create the parser for the "a" command
    parser_a = subparsers.add_parser('a', help='a help')
    parser_a.add_argument('bar', type=int, help='bar help')
    
    # create the parser for the "b" command
    parser_b = subparsers.add_parser('b', help='b help')
    parser_b.add_argument('--baz', choices='XYZ', help='baz help')
    # print main help
    print(parser.format_help())
    
    # retrieve subparsers from parser
    subparsers_actions = [
        action for action in parser._actions 
        if isinstance(action, argparse._SubParsersAction)]
    # there will probably only be one subparser_action,
    # but better safe than sorry
    for subparsers_action in subparsers_actions:
        # get all subparsers and print help
        for choice, subparser in subparsers_action.choices.items():
            print("Subparser '{}'".format(choice))
            print(subparser.format_help())
    

    This example should work for python 2.7 and python 3. The example parser is from Python 2.7 documentation on argparse sub-commands.

    The only thing left to do is adding a new argument for the complete help, or replacing the built in -h/--help.

提交回复
热议问题