I am writing a python script that takes two arguments, and some options:
scriptname [-h] [-l] [-q|-d] arg1 arg2
The -q
(quiet) and -d
(debug) options change the verbosity level, and the -h
option is the help option automatically created by argparse.
I would like the -l
(list) option to behave similarly to the -h
option in that it will not require that the (otherwise mandatory) arguments are present and list some useful information (different from the -h
option). In practice, this means that the script could be called in the following three ways:
scriptmane [-q|-d] arg1 arg2
scriptname -l
scriptname -h
Two possible ways forward would be to:
-l
og -h
options are not given.But I hope there is a more straightforward way to inherit the "this option is all you need" behaviour from the help option.
Solution (based on samwyse's answer):
Based on the _HelpAction()
in argparse.py:
class _ListAction(argparse.Action):
def __init__(self,
option_strings,
dest=argparse.SUPPRESS,
default=argparse.SUPPRESS,
help=None):
super(_ListAction, self).__init__(
option_strings=option_strings,
dest=dest,
default=default,
nargs=0,
help=help)
def __call__(self, parser, namespace, values, option_string=None):
print_list()
parser.exit()
and then, during parser setup:
parser.add_argument('-l', '--list', action=_ListAction,
help="List all available cases")
To add an optional argument, simply omit the required parameter in add_argument() . args = parser. parse_args()if args.
Using argparse is how you let the user of your program provide values for variables at runtime. It's a means of communication between the writer of a program and the user. That user might be your future self. 😃 Using argparse means the doesn't need to go into the code and make changes to the script.
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.
The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.
In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line. To make an option required, True can be specified for the required= keyword argument to add_argument ():
>>> parser = argparse.ArgumentParser(description='Process some integers.') The ArgumentParser object will hold all the information necessary to parse the command line into Python data types. Filling an ArgumentParser with information about program arguments is done by making calls to the add_argument () method.
There are many advantages of Argparse. For example, it is a Python built-in module that doesn’t need to be downloaded and installed. However, the drawbacks are also obvious. 1. It has built-in behaviour to guess if something is an argument or an option.
If the option "list" is intended to have different behavior from "help" then you need to write a custom action. The good news is that it is very simple to do this. The main page for argparse gives you hints, you only have to realize that the action is called as soon as the option is seen in the list of arguments. In the new action's call (that should have two underscores at each end but markdown uses those for emphasis) method, do whatever you need to do for your option and then call parser.exit() to short circuit the processing of any more arguments.
Look at the source for _HelpAction and _VersionAction here: https://github.com/ThomasWaldmann/argparse/blob/master/argparse.py (and probably just subclass one of them to skip writing the init code).
You can easily do this with argparse
. The following will support both -l
and --list
as additional help options:
parser.add_argument("-l", "--list", action="help")
If you don't want to support the long form (--list
), simply omit it from the argument list.
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