Permit argparse global flags after subcommand

前端 未结 3 2339
情话喂你
情话喂你 2021-02-19 18:20

I am using argparse to build a command with subcommands:

mycommand [GLOBAL FLAGS] subcommand [FLAGS]

I would like the global flags to work whether they are befor

3条回答
  •  萌比男神i
    2021-02-19 18:32

    This is a perfect use case for parents argparse feature:

    Sometimes, several parsers share a common set of arguments. Rather than repeating the definitions of these arguments, a single parser with all the shared arguments and passed to parents= argument to ArgumentParser can be used.

    Define a base parent ArgumentParser, add arguments that will be shared across subparsers. Then, add subparsers and set your base parser as a parent by providing parents keyword argument:

    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subparser_name')
    
    base_subparser = argparse.ArgumentParser(add_help=False)
    # define common shared arguments
    base_subparser.add_argument('--disable')
    
    sp = subparsers.add_parser('compile', parents=[base_subparser])
    # define custom arguments
    sp = subparsers.add_parser('launch', parents=[base_subparser])
    # define custom arguments
    

    Note that add_help=False here helps to avoid problems with conflicting help argument.

    Also see: Python argparse - Add argument to multiple subparsers.

提交回复
热议问题