Get selected subcommand with argparse

前端 未结 2 1839
[愿得一人]
[愿得一人] 2020-12-07 13:50

When I use subcommands with python argparse, I can get the selected arguments.

parser = argparse.ArgumentParser()
parser.add_argument(\'-g\', \'--global\')
s         


        
相关标签:
2条回答
  • 2020-12-07 14:05

    ArgumentParser.add_subparsers has dest formal argument described as:

    dest - name of the attribute under which sub-command name will be stored; by default None and no value is stored

    In the example below of a simple task function layout using subparsers, the selected subparser is in parser.parse_args().subparser.

    import argparse
    
    
    def task_a(alpha):
        print('task a', alpha)
    
    
    def task_b(beta, gamma):
        print('task b', beta, gamma)
    
    
    if __name__ == '__main__':
        parser = argparse.ArgumentParser()
        subparsers = parser.add_subparsers(dest='subparser')
    
        parser_a = subparsers.add_parser('task_a')
        parser_a.add_argument(
            '-a', '--alpha', dest='alpha', help='Alpha description')
    
        parser_b = subparsers.add_parser('task_b')
        parser_b.add_argument(
            '-b', '--beta', dest='beta', help='Beta description')
        parser_b.add_argument(
            '-g', '--gamma', dest='gamma', default=42, help='Gamma description')
    
        kwargs = vars(parser.parse_args())
        globals()[kwargs.pop('subparser')](**kwargs)
    
    0 讨论(0)
  • 2020-12-07 14:27

    The very bottom of the Python docs on argparse sub-commands explains how to do this:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('-g', '--global')
    >>> subparsers = parser.add_subparsers(dest="subparser_name") # this line changed
    >>> foo_parser = subparsers.add_parser('foo')
    >>> foo_parser.add_argument('-c', '--count')
    >>> bar_parser = subparsers.add_parser('bar')
    >>> args = parser.parse_args(['-g', 'xyz', 'foo', '--count', '42'])
    >>> args
    Namespace(count='42', global='xyz', subparser_name='foo')
    

    You can also use the set_defaults() method referenced just above the example I found.

    0 讨论(0)
提交回复
热议问题