argparse optional subparser (for --version)

前端 未结 7 1389
长情又很酷
长情又很酷 2020-12-09 03:38

I have the following code (using Python 2.7):

# shared command line options, like --version or --verbose
parser_shared = argparse.ArgumentParser(add_help=Fal         


        
7条回答
  •  余生分开走
    2020-12-09 04:36

    As discussed in http://bugs.python.org/issue9253 (argparse: optional subparsers), as of Python 3.3, subparsers are now optional. This was an unintended result of a change in how parse_args checked for required arguments.

    I found a fudge that restores the previous (required subparsers) behavior, explicitly setting the required attribute of the subparsers action.

    parser = ArgumentParser(prog='test')
    subparsers = parser.add_subparsers()
    subparsers.required = True   # the fudge
    subparsers.dest = 'command'
    subparser = subparsers.add_parser("foo", help="run foo")
    parser.parse_args()
    

    See that issue for more details. I expect that if and when this issue gets properly patched, subparsers will be required by default, with some sort of option to set its required attribute to False. But there is a big backlog of argparse patches.

提交回复
热议问题