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 level of detail, and the -h option is a help option automatically created using argparse.
I would like the -l (list) option to behave similarly to the -h option in that it does not require (otherwise required) arguments and lists some useful information (other than the -h option). In practice, this means that the script can be called in three ways:
scriptmane [-q|-d] arg1 arg2 scriptname -l scriptname -h
Two possible ways forward:
- Make the arguments optional (with nargs = '?') And add code to make sure that there are two arguments in all cases where the
-l og -h options are not specified. - Write a custom action class (unsure of the details).
But I hope that there is an easier way to inherit the behavior "this option is all you need" from the help option.
Solution (based on samwyse answer):
Based on _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 configuration:
parser.add_argument('-l', '--list', action=_ListAction, help="List all available cases")