How can I disable printing subcommand choices, the ones between curly brackets? Using an example at http://docs.python.org/dev/library/argparse.html#sub-commands, the normal output is:
usage: [-h] {foo,bar} ...
optional arguments:
-h, --help show this help message and exit
subcommands:
{foo,bar} additional help
What I want is to print this:
usage: [-h] {foo,bar} ...
optional arguments:
-h, --help show this help message and exit
subcommands:
Removing just the last line.
I would use a print call like the following print(' {} {}'. format(arg, getattr(args, arg) or '')) with getattr(args, arg) or '' being the essential difference to your version to prevent the word 'None' from being printed in case of unused optional parameters.
Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser.
The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv .
1.1 Positional and Optional Arguments Provide a positional and an optional argument. Position arguments are provided positions when the module is called, without prefixed by which parameter this is. Optional argument requires parameter specification.
To avoid spamming my users with the huge ugly curly-braced list of dozens of sub-commands, I simply set the metavar
attribute of the subcommand object. My code looks like:
import argparse
parser = argparse.ArgumentParser(description='Stack Overflow example')
subs = parser.add_subparsers()
subs.metavar = 'subcommand'
sub = subs.add_parser('one', help='does something once')
sub = subs.add_parser('two', help='does something twice')
parser.parse_args()
And the output of running this script with a single -h
argument is:
usage: tmp.py [-h] subcommand ...
Stack Overflow example
positional arguments:
subcommand
one does something once
two does something twice
optional arguments:
-h, --help show this help message and exit
The result is not exactly what you illustrate as your best desired case, but I think that it may be the closest you can get without subclassing argparse.ArgumentParser
and overriding the things you need adjusted, which would be messy work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With