How about using parser.parse_known_args()
method and then adding the --lport
and --rport
args as required args if --prox
is present.
# just add --prox arg now
non_int = argparse.ArgumentParser(description="stackoverflow question",
usage="%(prog)s [-h] [--prox --lport port --rport port]")
non_int.add_argument('--prox', action='store_true',
help='Flag to turn on proxy, requires additional args lport and rport')
opts, rem_args = non_int.parse_known_args()
if opts.prox:
non_int.add_argument('--lport', required=True, type=int, help='Listen Port.')
non_int.add_argument('--rport', required=True, type=int, help='Proxy port.')
# use options and namespace from first parsing
non_int.parse_args(rem_args, namespace = opts)
Also keep in mind that you can supply the namespace opts
generated after the first parsing while parsing the remaining arguments the second time. That way, in the the end, after all the parsing is done, you'll have a single namespace with all the options.
Drawbacks:
- If
--prox
is not present the other two dependent options aren't even present in the namespace. Although based on your use-case, if --prox
is not present, what happens to the other options is irrelevant.
- Need to modify usage message as parser doesn't know full structure
--lport
and --rport
don't show up in help message