metavar can 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 not displayed in use or in help. But it appears in the error message
error: argument {cmd1, cmd2}: wrong choice: 'cmd' (choose from 'cmd1', 'cmd2', 'cmd3')
You may already have discovered this use of help=SUPPRESS . But this requires user-use parameters (and possibly descriptions):
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()
In the main parser, subparameters look like choices positional argument. As far as I can tell, there is no way to selectively suppress choices .
At this level of question, learning the argparse.py code argparse.py may be more useful than docs. In this case, I looked at the code for class _SubParsersAction(Action) . This is doubly true if you want to configure the formatter. Existing alternative formats modify only one or two methods, deeply immersed in the class.
This issue was raised as a bug, http://bugs.python.org/issue22848 .
There is a patch that will change the display of choices based on help=SUPPRESS for individual subparameters. But I recommend the metavar solution, at least for now. There are other suggested fixes for working with choices .
source share