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?
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
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.
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.
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/
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
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