python argparse具有不同参数数量的不同参数 [英] python argparse different parameters with different number of arguments
问题描述
如何为每个选项使用不同数量的参数?
How do I use a different number of parameters for each option?
例如) a.py
parser.add_argument('--opt', type=str,choices=['a', 'b', 'c'],help='blah~~~')
- 选择:a/参数:1
例如)
$ python a.py --opt a param
- 选择:c/参数:2
例如)
$ python a.py --opt b param1 param2
推荐答案
您可以添加更多参数,每个 a、b 和 c 一个,以及您的 params 的可选参数.通过使用命名参数 nargs='?'您可以指定它们是可选的,并且使用 default="some value" 确保它不会出现错误.最后,根据选择的选项 a、b 或 c,您将能够捕获您需要的选项.
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.
干杯
这篇关于python argparse具有不同参数数量的不同参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!