In the python module argparse, how can I turn off the selection of the print subcommand between curly braces?

How can I turn off the selection of a print subcommand, i.e. between curly braces? Using the example 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 

I want to print this:

 usage: [-h] {foo,bar} ... optional arguments: -h, --help show this help message and exit subcommands: 

Delete only the last line.

+6
source share
2 answers

To avoid spamming my users with a huge ugly interspersed list of dozens of subcommands, I simply set the metavar attribute of the metavar object. My code looks like this:

 import argparse parser = argparse.ArgumentParser(description='Qaru 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:

 usage: tmp.py [-h] subcommand ... Qaru 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 will illustrate as your best-desired case, but I think it might be the closest you can get without subclassing argparse.ArgumentParser and overriding what you need to configure, which would be dirty work.

+6
source

Override ArgumentParser.print_usage () using your own print method of any way you want. If all you want to do is delete the last line, call the original version, capture the results (sending them to a file) and print only the parts that you want.

0
source

Source: https://habr.com/ru/post/906715/


All Articles