To clarify the approach of the subparameter:
sp = parser.add_subparsers(dest='a') x = sp.add_parser('x') y=sp.add_parser('y') z=sp.add_parser('z') x.add_argument('-b', required=True)
- this differs from your specification in that
-a is not required. Argument dest='a' ensures that the attribute 'a' is in the namespace.- usually the optional parameter '-b' is not required. Subparser 'x' can also take the required position.
If you must use the -a optional option, two-step parsing may work
p1 = argparse.ArgumentParser() p1.add_argument('-a',choices=['x','y','z']) p2 = argparse.ArgumentParser() p2.add_argument('-b',required=True) ns, rest = p1.parse_known_args() if ns.a == 'x': p2.parse_args(rest, ns)
The third approach is to do your own test after the fact. You can still use argparse error mechanism
parser.error('-b required with -a x')
source share