Select Page

As part of the day job, I end up writing a lot of command utility-type scripts (programs). These are often scripts that are used very occasionally, like once per quarter. By the time a script is going to be reused, I have often forgotten what the script does and what input elements it needs. (Like nostalgia, my memory ain’t what it used to be!)

To solve this problem of forgotten functionality, I like to make use of Python’s argument parsing module, argparse.

In the example below we will look at a little example script that I put together to show some of the basic usage techniques of argparse. Let’s start with a look at the end product of this example, which is the “help” output that the program will write on the screen when requested:

As we’ll see below, I did provide some [hopefully] help text, but argparse does a bunch of work to display information about the expected parameters. In addition to explaining the parameters, argparse will also verify that those are the actual parameters…both documentation and validation…I love it!

So let’s take a look at a little bit of code. This is like a sort of preamble to the actual argparse code.

We start out by importing the tools we are going to need (RawTextHelpFormatter will let us print our help text more easily). The script has an interpolated string that contains the help we want to show the user (or show our future selves!). The text is primarily help, but I like to keep the script name dynamic ({file}) because I often end up renaming scripts.

We’re ready to create our argument parser and add our first few argument specifications.

The first line creates our argument parser instance and assigns it the helpful text from d. We’re specifying the formatter_class using the built-in RawTextHelpFormatter so that our help text will be displayed nicely, maintaining the multiple lines I have intentionally specified.

The second line is creating a simple argument to the script. The user can specify -m or --filemask, interchangeably, on the command line. By default the argument is optional. The help text is displayed by argparse when the user requests help by using the -h command line switch. Not surprisingly, the default value is specified as well. We’ll look below at how to read these values from the set of all arguments.

The third line makes use of a very cool feature of the parser. In this case, we are specifying that the user can pairs of arguments to the program. The nargs parameter specifies that we want our arguments to come in pairs. So, for example -r preston yves is a pair of arguments, with “preston” as the “target” and “yves” as the “replacement”. Because we want the user to be able to supply any number of -r arguments, we need to tell argparse how to handle the presence of multiple values and we do this by indicating action='append'. Later, we will see a list of parameters in our replace variable.

We move on to take a look at a group of mutually exclusive parameters. In our example, we have a “verbose” or “quiet” option. We are requiring the user to specify one option or the other and making sure that they don’t do something nonsensical like specifying both options.

The first line creates mutually exclusive group within our already-existing parser. We are also specifying that required=True which may be overkill but it’s useful for this example.

Specifying arguments within a group is pretty similar to specifying the arguments in the higher level parser. In this example, a key feature to notices is that both -v and -q specify dest='verbose_mode'. That means that the value from the arguments will be stored in a verbose_mode variable. We’re also specifying that we want True or False saved in the variable by specifying action='store_true' or action='store_false'.

After we have specified the rules for the argument parser, we are ready to parse the command line arguments and start reading our variables.

We start by having the parser do our work and load up our variables. (Hooray for the giants that preceded us!). That’s the real work. The parser does the validation and will kill the program with a helpful error message if the arguments do not meet the requirements.

The args.filemask variable contains the value passed in with the -m argument. The default value is assigned if the user does not provide a specific value.

The args.verbose_mode variable contains the appropriate value from the mutually exclusive -v and -q arguments. If we had wanted a different variable then we would have specified a different dest values when we created the arguments.

The -r argument specified that we wanted the arguments to be appended (action='append'). As a result, we have a list of arguments that are stored in args.replace. We check to make sure the variable exists and then we can iterate through the list and look at the “target” and “replacement” values that the user specified on the command line.

Being able to take advantage of a built-in feature to verify and validate our script arguments is huge. It’s terrific to know, inside the program, that the user has given us good information and we don’t need to do much to guarantee that it’s all safe to proceed!

Feel free to use the example program yourself.

Share This