I've created an argparse argument, which supports only 3 choices:
parser.add_argument('--param', default='ch1', choices=('ch1', 'ch2', 'ch3'), help='message')
But I have to add a new special choice ch4 which will require an additional value.
I.e., my program should support such inputs:
./prog.py --param ch1
./prog.py --param ch2 # or ch3
./prog.py --param ch4='some_additional_variable'
How I can realize this (or some similar behavior)?
You can workaround it by requiring an additional argument if ch4 param is set:
import argparse
parser = argparse.ArgumentParser(description='...')
parser.add_argument('--param', default='ch1', choices=('ch1', 'ch2', 'ch3', 'ch4'))
parser.add_argument('--setting', help="Required if param is set to ch4")
args = parser.parse_args()
if args.param == "ch4" and not args.setting:
parser.error("--setting is required if param is ch4")
Usage:
$ python test.py --param ch1
$ python test.py --param ch2
$ python test.py --param ch3
$ python test.py --param ch4
usage: test.py [-h] [--param {ch1,ch2,ch3,ch4}] [--setting SETTING]
test.py: error: --setting is required if param is ch
$ python test.py --param ch4 --setting "some_value"
$
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