Python argparse help-like option

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") 
+6
source share
2 answers

If the "list" option is designed for different behaviors using "help", you need to write your own action. The good news is that it is very easy to do. The main page for argparse gives you hints, you only need to understand that the action is called as soon as the option is displayed in the argument list. In a new action call (which should have two underscores at each end, but markdown uses methods to highlight) do everything you need to do for your option, and then call parser.exit () to shorten the processing of any additional arguments.

Take a look at the source of _HelpAction and _VersionAction here: https://github.com/ThomasWaldmann/argparse/blob/master/argparse.py (and maybe just subclass one of them to skip the initialization code entry).

+3
source

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 do not want to maintain a long form ( --list ), just omit it from the argument list.

+1
source

All Articles