Below are three arguments I am writing in a module.
parser.add_argument('--Type',type=str,choices=['a','b','c'],help='Options include: a,b,c.',required=True)
parser.add_argument('--Input',default=False,help='Generate input files',required=False)
parser.add_argument('--Directory',default=False,help='Secondary directory',required='--Input' in sys.argv)
The --Type
is possible with three options: a,b,c.
Currently, I have it set up so that, if --Directory is true, it requires --Input to be true.
However, I would like add an additional condition to --Directory to require --Type to be == 'c'.
How do I alter the required option in the --Directory argument so that it needs both --Input and --Type == 'c'?
Decouple argument parsing from your requirements.
parser.add_argument('--Type', choices=['a','b','c'], required=True)
parser.add_argument('--Input', action='store_true')
parser.add_argument('--Directory', action='store_true')
args = parser.parse_args()
if args.Directory and args.Type != 'c' and not args.input:
raise argparse.ArgumentError("--Directory requires --Type c and --Input")
(Note that action='store_true'
automatically sets type=bool
and default=False
.)
I would not use the required
parameter for either of those things, it is kind of error-prone and not very readable. Just check the validity of the arguments after parsing.
import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--Type', type=str, choices=['a','b','c'], help='Options include: a,b,c.', required=True)
parser.add_argument('--Input', default=False, help='Generate input files', required=False)
parser.add_argument('--Directory', default=False, help='Secondary directory', required=False)
parsed_args = parser.parse_args()
if parsed_args.Directory and not (parsed_args.Input and parsed_args.Type == 'c'):
parser.error('option --Directory requires --Input and --Type c.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With