In my python script, I want to be able to use an optional input parameter only when another optional parameter has been specified. Example:
$ python myScript.py --parameter1 value1
$ python myScript.py --parameter1 value1 --parameter2 value2
But NOT:
$ python myScript.py --parameter2 value2
How do I do this with argparse?
Thanks!
Use a custom action:
This can even be done in a little easier to maintain way if you’re OK with relying on some undocumented behavior of argparse:
In this example, we get the default for
fooand it’s destination from the action object returned byadd_argument(add_argument’s return value isn’t documented anywhere that I can find). This is still a little fragile (If you want to specify atype=keyword to the--fooargument for example).Finally, you can check
sys.argvbefore parsing.This gets a little more tricky if
--parameter1could also be triggered by--p1, but you get the idea. Then you could useThe advantage here is that it doesn’t require any particular order. (
--p2doesn’t need to follow--p1on the commandline). And, as before, you can get the list of command strings that will trigger your particular action via theoption_stringsattribute returned byparser.add_argument(...). e.g.