Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In python's argparse module, how can I disable printing subcommand choices between curly brackets?

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.

like image 797
Thiago Padilha Avatar asked Jan 24 '12 00:01

Thiago Padilha


People also ask

How do you print args from Argparse Python?

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.

How do you make an argument optional in Argparse?

Optional Arguments To add an optional argument, simply omit the required parameter in add_argument() . args = parser.

What is the use of ArgumentParser () in Python?

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 .

What are positional and optional arguments in Argparse?

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.


1 Answers

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.

like image 138
Brandon Rhodes Avatar answered Sep 29 '22 19:09

Brandon Rhodes