Python Argparse Different Parameters With Different Number Of Arguments
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~~~') choice : a / parameter : 1
Solution 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)
Solution 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
Post a Comment for "Python Argparse Different Parameters With Different Number Of Arguments"