metavar
might do the trick:
import argparse
parser = argparse.ArgumentParser()
sp = parser.add_subparsers(metavar='{cmd1,cmd2}')
sp1 = sp.add_parser('cmd1')
sp2 = sp.add_parser('cmd2')
sp3 = sp.add_parser('cmd3')
parser.parse_args()
With this cmd3
does not appear in the usage or help. But it does appear in the error message
error: argument {cmd1,cmd2}: invalid choice: 'cmd' (choose from 'cmd1', 'cmd2', 'cmd3')
You may have already discovered this use of help=SUPPRESS
. But it requires a custom usage (and possibly description) parameters:
import argparse
parser = argparse.ArgumentParser(usage='%(prog)s [-h] {cmd1,cmd2}')
sp = parser.add_subparsers(help=argparse.SUPPRESS)
sp1 = sp.add_parser('cmd1')
sp2 = sp.add_parser('cmd2')
sp3 = sp.add_parser('cmd3')
parser.parse_args()
To the main parser, subparsers look like choices
of a positional argument. As best I can tell there isn't a way of selectively suppressing choices
.
With this level of question, examining the argparse.py
code itself can be more help than the docs. In this case I looked at the code for class _SubParsersAction(Action)
. That's doubly true if you want to customize the formatter. The existing alternative formatters modify just one or two methods buried deep in the class.
This issue has been raised as a bug issue, http://bugs.python.org/issue22848.
There is a patch that would modify the choices display based on help=SUPPRESS
for individual subparsers. But I'm recommending the metavar
solution, at least for now. There are other proposed patches for dealing with choices
.