With the following code:
import argparse
parser = argparse.ArgumentParser(description="Prepare something code.")
parser.add_argument("-t","--tabular", help="print something in tabular way for EXCEL",
action="store_true")
parser.add_argument("-v","--verbose", action="store_true")
args = parser.parse_args()
if args.tabular:
print "Tabular print"
elif args.verbose:
print "VERBOSE"
It's only when I execute it the following way, that it prints usage:
$ python mycode.py -h
usage: mycode.py [-h] [-t] [-v]
Prepare something code.
optional arguments:
-h, --help show this help message and exit
-t, --tabular print something in tabular way for EXCEL
-v, --verbose
What I want to do is to simply run the code: $ my code.py
without any -h
option whatsoever to print the usage. How can I do that?
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
The argparse module provides a convenient interface to handle command-line arguments. It displays the generic usage of the program, help, and errors. The parse_args() function of the ArgumentParser class parses arguments and adds value as an attribute dest of the object.
Adding arguments Later, calling parse_args() will return an object with two attributes, integers and accumulate . The integers attribute will be a list of one or more ints, and the accumulate attribute will be either the sum() function, if --sum was specified at the command line, or the max() function if it was not.
Metavar: It provides a different name for optional argument in help messages.
That 2010 question covers the same thing, but only has 1 answer. While that answer comes indirectly from the designer of argparse
, it does not cover all possibilities.
Here's one which surprised me as to its simplicity:
import sys
parser = ...
if len(sys.argv)==1:
parser.print_help()
# parser.print_usage() # for just the usage line
parser.exit()
args = parser.parse_args()
Yes you can check all the namespace
args for default values, but that gets old if there are many arguments. But here I am just checking whether there are any argument strings. If none, then call the parser's own help function.
ipython
does something like this to generate help. It checks sys.argv
for some version of help
, and produces its own help message(s), before even defining the parser
.
import argparse
parser = argparse.ArgumentParser(description="Prepare something code.")
parser.add_argument("-t","--tabular", help="print something in tabular way for EXCEL",
action="store_true")
parser.add_argument("-v","--verbose", action="store_true")
args = parser.parse_args()
if args.tabular:
print "Tabular print"
elif args.verbose:
print "VERBOSE"
else:
print parser.print_help()
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