Given a small parser:
from argparse import ArgumentError, ArgumentParser
p = ArgumentParser()
p.add_argument('x', choices=['1', '2'])
p.add_argument('--y', required=False)
p.parse_args('1 --y 2'.split()) # this would work
p.parse_args('1'.split()) # this would work also
However, I want to ensure that if x=='1'
, then --y
would get a value. My implementation was this:
args = p.parse_args('1 --y 2'.split())
if args.x=='1' and not args.y:
raise ArgumentError('blah')
Is there an inner argparse way to do this? it looks much better when argparse throws a parsing error
Even better, I want the --y
arg will be required when x=='1'
and not allowed when x=='2'