fork download
  1. from __future__ import print_function
  2.  
  3. from argparse import ArgumentParser
  4. from random import randint
  5.  
  6.  
  7. def get_parser():
  8. # create the top-level parser
  9. parser = ArgumentParser(prog='PROG')
  10. subparsers = parser.add_subparsers(help='sub-command help')
  11.  
  12. # create the parser for the "sum" command
  13. parser_a = subparsers.add_parser('sum_cmd', help='sum some integers')
  14. parser_a.add_argument('-a', type=int,
  15. help='an integer for the accumulator')
  16. parser_a.add_argument('-b', type=int,
  17. help='an integer for the accumulator')
  18. parser_a.add_argument('--sum', dest='sm', action='store_const',
  19. const=sum, default=max,
  20. help='sum the integers (default: find the max)')
  21.  
  22. # create the parser for the "min" command
  23. parser_b = subparsers.add_parser('min_cmd', help='min some integers')
  24. parser_b.add_argument('-y', type=float,
  25. help='an float for the accumulator')
  26. parser_b.add_argument('-z', type=float,
  27. help='an float for the accumulator')
  28. parser_b.add_argument('--min', dest='mn', action='store_const',
  29. const=min, default=0,
  30. help='smallest integer (default: 0)')
  31. return parser
  32.  
  33.  
  34. if __name__ == '__main__':
  35. parser = get_parser()
  36.  
  37. input_sum_cmd = ['sum_cmd', '--sum']
  38. input_min_cmd = ['min_cmd', '--min']
  39.  
  40. args, rest = parser.parse_known_args(
  41. # `sum`
  42. input_sum_cmd +
  43. ['-a', str(randint(21, 30)),
  44. '-b', str(randint(51, 80))] +
  45. # `min`
  46. input_min_cmd +
  47. ['-y', str(float(randint(64, 79))),
  48. '-z', str(float(randint(91, 120)) + .5)]
  49. )
  50.  
  51. print('args:\t ', args,
  52. '\nrest:\t ', rest, '\n', sep='')
  53.  
  54. sum_cmd_result = args.sm((args.a, args.b))
  55. print(
  56. 'a:\t\t {:02d}\n'.format(args.a),
  57. 'b:\t\t {:02d}\n'.format(args.b),
  58. 'sum_cmd: {:02d}\n'.format(sum_cmd_result), sep='')
  59.  
  60. assert rest[0] == 'min_cmd'
  61. args = parser.parse_args(rest)
  62. min_cmd_result = args.mn((args.y, args.z))
  63. print(
  64. 'y:\t\t {:05.2f}\n'.format(args.y),
  65. 'z:\t\t {:05.2f}\n'.format(args.z),
  66. 'min_cmd: {:05.2f}'.format(min_cmd_result), sep='')
  67.  
Success #stdin #stdout 0.02s 10984KB
stdin
Standard input is empty
stdout
args:	 Namespace(a=23, b=80, sm=<built-in function sum>)
rest:	 ['min_cmd', '--min', '-y', '76.0', '-z', '96.5']

a:		 23
b:		 80
sum_cmd: 103

y:		 76.00
z:		 96.50
min_cmd: 76.00