0

I am writing a script that accepts multiple arguments, some are optional but should be provided together, how can I achieve this behaviour?

Ex: arg1 is a required argument

opt-arg-1 and opt-arg-2 should be provided together or none at all

python my_script.py --arg1 val1 # Works fine
python my_script.py --arg1 val1 --opt-arg-1 other_val # Error both opt-arg-1 and opt-arg-2 should be provided
python my_script.py --arg1 val1 --opt-arg-2 other_val # Error both opt-arg-1 and opt-arg-2 should be provided
python my_script.py --arg1 val1 --opt-arg-1 other_val --opt-arg-2 other_val_2 # Works fine
arnino
  • 441
  • 2
  • 14
  • The easiest way is to raise your own error when all of the optional arguments are not given together. Just set the default value of each to `None` and if all optional arguments are `None` or all of them are not `None` you can proceed. – Barış Aktaş Feb 01 '23 at 14:31
  • How about defining one optional argument with `nargs=2`? – hpaulj Feb 01 '23 at 16:16
  • Does this answer your question? [Python Argparse conditionally required arguments](https://stackoverflow.com/questions/25626109/python-argparse-conditionally-required-arguments) – blues Feb 09 '23 at 14:26

0 Answers0