Permit argparse global flags after subcommand

前端 未结 3 2355
情话喂你
情话喂你 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条回答
  •  灰色年华
    2021-02-19 18:43

    I see two issues in your example:

    1) The use of '--disable' in both the parser and subparsers. Nested ArgumentParser deals with that overlapping dest.

    2) The repeated set of arguments in the subparsers. parents is certainly one way to simplify that. But you could easily write your own code:

    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers(dest='subparser_name')
    
    parser.add_argument('--disable', dest='main_disable')    # This flag...
    
    for name in ['compile', 'launch']:
        sp = subparsers.add_parser(name)
        sp.add_argument('zones', nargs='*')
        sp.add_argument('--disable', dest=name+'_disable')        # Is repeated...
    

提交回复
热议问题