How to parse multiple nested sub-commands using python argparse?

后端 未结 11 1122
执念已碎
执念已碎 2020-11-28 20:52

I am implementing a command line program which has interface like this:

cmd [GLOBAL_OPTIONS] {command [COMMAND_OPTS]} [{command [COMMAND_OPTS]} ...]
<         


        
11条回答
  •  醉酒成梦
    2020-11-28 21:24

    Built a full Python 2/3 example with subparsers, parse_known_args and parse_args (running on IDEone):

    from __future__ import print_function
    
    from argparse import ArgumentParser
    from random import randint
    
    
    def main():
        parser = get_parser()
    
        input_sum_cmd = ['sum_cmd', '--sum']
        input_min_cmd = ['min_cmd', '--min']
    
        args, rest = parser.parse_known_args(
            # `sum`
            input_sum_cmd +
            ['-a', str(randint(21, 30)),
             '-b', str(randint(51, 80))] +
            # `min`
            input_min_cmd +
            ['-y', str(float(randint(64, 79))),
             '-z', str(float(randint(91, 120)) + .5)]
        )
    
        print('args:\t ', args,
              '\nrest:\t ', rest, '\n', sep='')
    
        sum_cmd_result = args.sm((args.a, args.b))
        print(
            'a:\t\t {:02d}\n'.format(args.a),
            'b:\t\t {:02d}\n'.format(args.b),
            'sum_cmd: {:02d}\n'.format(sum_cmd_result), sep='')
    
        assert rest[0] == 'min_cmd'
        args = parser.parse_args(rest)
        min_cmd_result = args.mn((args.y, args.z))
        print(
            'y:\t\t {:05.2f}\n'.format(args.y),
            'z:\t\t {:05.2f}\n'.format(args.z),
            'min_cmd: {:05.2f}'.format(min_cmd_result), sep='')
    
    def get_parser():
        # create the top-level parser
        parser = ArgumentParser(prog='PROG')
        subparsers = parser.add_subparsers(help='sub-command help')
    
        # create the parser for the "sum" command
        parser_a = subparsers.add_parser('sum_cmd', help='sum some integers')
        parser_a.add_argument('-a', type=int,
                              help='an integer for the accumulator')
        parser_a.add_argument('-b', type=int,
                              help='an integer for the accumulator')
        parser_a.add_argument('--sum', dest='sm', action='store_const',
                              const=sum, default=max,
                              help='sum the integers (default: find the max)')
    
        # create the parser for the "min" command
        parser_b = subparsers.add_parser('min_cmd', help='min some integers')
        parser_b.add_argument('-y', type=float,
                              help='an float for the accumulator')
        parser_b.add_argument('-z', type=float,
                              help='an float for the accumulator')
        parser_b.add_argument('--min', dest='mn', action='store_const',
                              const=min, default=0,
                              help='smallest integer (default: 0)')
        return parser
    
    
    if __name__ == '__main__':
        main()
    

提交回复
热议问题