argparse optional subparser (for --version)

前端 未结 7 1390
长情又很酷
长情又很酷 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:22

    Yeah, I just checked svn, which is used as an object example in the add_subparsers() documentation, and it only supports '--version' on the main command:

    python zacharyyoung$ svn log --version
    Subcommand 'log' doesn't accept option '--version'
    Type 'svn help log' for usage.
    

    Still:

    # create common parser
    parent_parser = argparse.ArgumentParser('parent', add_help=False)
    parent_parser.add_argument('--version', action='version', version='%(prog)s 2.0')
    
    # create the top-level parser
    parser = argparse.ArgumentParser(parents=[parent_parser])
    subparsers = parser.add_subparsers()
    
    # create the parser for the "foo" command
    parser_foo = subparsers.add_parser('foo', parents=[parent_parser])
    

    Which yields:

    python zacharyyoung$ ./arg-test.py --version
    arg-test.py 2.0
    python zacharyyoung$ ./arg-test.py foo --version
    arg-test.py foo 2.0
    

提交回复
热议问题