Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Control formatting of the argparse help argument list?

import argparse parser = argparse.ArgumentParser(prog='tool') args = [('-u', '--upf', 'ref. upf', dict(required='True')),         ('-s', '--skew', 'ref. skew', {}),         ('-m', '--model', 'ref. model', {})] for args1, args2, desc, options in args:        parser.add_argument(args1, args2, help=desc, **options)  parser.print_help() 

Output:

usage: capcheck [-h] -u UPF [-s SKEW] [-m MODEL]  optional arguments:   -h, --help            show this help message and exit   -u UPF, --upf UPF     ref. upf   -s SKEW, --skew SKEW  ref. skew   -m MODEL, --model MODEL                         ref. model 

How do I print ref. model in the same line as -m MODEL, --model MODEL instead of that appearing on a separate line when I run the script with -h option?

like image 564
Kaushik Balamukundhan Avatar asked Mar 28 '11 17:03

Kaushik Balamukundhan


People also ask

How do you make Argparse argument optional?

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

What does Nargs do in Argparse?

The add_argument() method action - The basic type of action to be taken when this argument is encountered at the command line. nargs - The number of command-line arguments that should be consumed. const - A constant value required by some action and nargs selections.

What is Store_true in Python?

The store_true option automatically creates a default value of False. Likewise, store_false will default to True when the command-line argument is not present.


1 Answers

You could supply formatter_class argument:

parser = argparse.ArgumentParser(prog='tool',   formatter_class=lambda prog: argparse.HelpFormatter(prog,max_help_position=27))  args = [('-u', '--upf', 'ref. upf', dict(required='True')),         ('-s', '--skew', 'ref. skew', {}),         ('-m', '--model', 'ref. model', {})] for args1, args2, desc, options in args:        parser.add_argument(args1, args2, help=desc, **options)  parser.print_help() 

Note: Implementation of argparse.HelpFormatter is private only the name is public. Therefore the code might stop working in future versions of argparse. File a feature request to provide a public interface for the customization of max_help_position on http://bugs.python.org/

Output

usage: tool [-h] -u UPF [-s SKEW] [-m MODEL]  optional arguments:   -h, --help               show this help message and exit   -u UPF, --upf UPF        ref. upf   -s SKEW, --skew SKEW     ref. skew   -m MODEL, --model MODEL  ref. model 
like image 117
jfs Avatar answered Sep 29 '22 12:09

jfs