Argparse: Is it possible to make the help context sensitive

1k Views Asked by At

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
1

There are 1 best solutions below

1
Eric O. Lebigot On

What you want to do is handled by argparse's sub-commands. Using sub-commands would imply replacing your --mode option with a sub-command:

prog --mode=1 OPTA OPTB OPTC

would become

prog mode1 OPTA OPTB OPTC

The mode1 sub-command can be given its own help; it is accessed with

prog mode1 -h

Another advantage of this approach is that prog -h lists the possible sub-commands (and an associated description).