I have a program that uses argparse to process the command line. The program's command line and hence it's help becomes context sensitive. I would like to make the help reflect that context sensitivity.
e.g.
prog --mode=1 OPTA OPTB OPTC<br>
prog --mode=2 OPTD OPTE OPTF<br>
prog --mode=1 -h<br>
"In mode 1 you have four options, A,B,C,D"
prog --mode=2 -h<br>
"You mode 2 you have four options, D,E,F,G"
I should add here that this is only an example. In my actual program there could be any number of modes and they are not defined by my code, they are defined by users of my API. Therefore it is impossible to hard code the help for each mode. The actual help text is defined later.
This means altering the help strings for the argument 'option' to reflect the different modes after the --mode argument has been processed. The code, below, basically works in that the command works as expected, but the help does not.
The problem is that parse_known_args() seems to handle the -h then exit. I need parse_args()
to handle the help. Obviously I could simple parse sys.argv
and find --mode
myself, but surely that defeats the object of argparse
.
import argparse
parser = argparse.ArgumentParser(description='Test argparser')
parser.add_argument('--mode', nargs=1, type=int,
default=[1],
help='program mode')
options={
1:["OPTA","OPTB","OPTC","OPTD"],
2:["OPTD","OPTE","OPTF","OPTG"]}
args = parser.parse_known_args()[0]
print "Initial pass"
print args
parser.add_argument('options', type=str, nargs='+',
choices=options[args.mode[0]]+["ALL"],
default="ALL",
help='One or more of the options, above')
args = parser.parse_args()
print "Second pass"
print args