python argparse different parameters with different number of arguments

╄→尐↘猪︶ㄣ 提交于 2019-12-12 04:58:16

问题


How do I use a different number of parameters for each option?

ex) a.py

parser.add_argument('--opt', type=str,choices=['a', 'b', 'c'],help='blah~~~')
  1. choice : a / parameter : 1

ex)

$ python a.py --opt a param
  1. choice : c / parameter :2

ex)

$ python a.py --opt b param1 param2

回答1:


You need to add sub-commands, ArgumentParser.add_subparsers() method will help you

Check this example

>>> # create the top-level parser
>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('--foo', action='store_true', help='foo help')
>>> subparsers = parser.add_subparsers(help='sub-command help')
>>>
>>> # create the parser for the "a" command
>>> parser_a = subparsers.add_parser('a', help='a help')
>>> parser_a.add_argument('bar', type=int, help='bar help')
>>>
>>> # create the parser for the "b" command
>>> parser_b = subparsers.add_parser('b', help='b help')
>>> parser_b.add_argument('--baz', choices='XYZ', help='baz help')
>>>
>>> # parse some argument lists
>>> parser.parse_args(['a', '12'])
Namespace(bar=12, foo=False)
>>> parser.parse_args(['--foo', 'b', '--baz', 'Z'])
Namespace(baz='Z', foo=True)



回答2:


You may add more parameters, one for each a, b, and c and also optional arguments for your params. By using the named parameter nargs='?' you can specify that they are optional and with the default="some value" you ensure it rises no errors. Finally, based on the selected option, a,b or c you will be able to capture the ones you need.

Here's a short usage example:

parser.add_argument('x1', type=float, nargs='?', default=0, help='Circ. 1 X-coord')
parser.add_argument('y1', type=float, nargs='?', default=0, help='Circ. 1 Y-coord')
parser.add_argument('r1', type=float, nargs='?', default=70, help='Circ. 1 radius')
parser.add_argument('x2', type=float, nargs='?', default=-6.57, help='Circ. 2 X-coord')
parser.add_argument('y2', type=float, nargs='?', default=7, help='Circ. 2 Y-coord')
parser.add_argument('r2', type=float, nargs='?', default=70, help='Circ. 2 radius')
args = parser.parse_args()

circCoverage(args.x1, args.y1, args.r1, args.x2, args.y2, args.r2)

here, if no values are selected, the default ones are used. You can play with this to get what you want.

Cheers



来源:https://stackoverflow.com/questions/45280057/python-argparse-different-parameters-with-different-number-of-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!