Argparse for CLI Intermediate Python Tutorial part 3

Welcome to part 3 of the intermediate Python programming tutorial series. In this part, we're going to talk about the standard library called argparse. Argparse is a parser for command-line options, arguments, and sub-commands.

In the basics series, we actually just used the sys library, which can also work, but isn't quite as extensive.

Having even just a very basic command-line interface (CLI) for your program can make everyone's life easier for modifying parameters, including programmers, but also non-programmers. A CLI for your program can also make it easier to automate running and modifying variables within your program, for when you want to run your program with a cronjob or maybe an os.system call. Let's make a super simple CLI as an example. Let's make a calculator program:

Nothing fancy there. Now, rather than interacting with this program via editing IDLE, we can actually interact with it on the command line. You could use something like input() for basic commands, but what if you wanted many optional commands? It just wouldn't work well. Instead, we'll add the following to the top of our script:

The above code will take arguments from the command line. The first parameter is basically the name of that argument, the next is the type of the variable, then a default, and finally a help parameter, just in case someone wants to be able to use -h. I will illustrate that momentarily. First, just note that, to build the command line parser, first we specify the parser, then we add arguments, then, the line that is args = parser.parse_args() is what ends up using that parser to grab the current args, whatever they are. Note as well that, at the end, we're using the sys module to do a stdout whatever the value of str(calc(args)) is.

Now, we just need to make a slight change to our initial calc function:

We could also have just redefined operation as being args.operation, and done the same with x and y, but this would result in copying the arguments. In the interest of efficiency, we're not going to do it, but a readability argument could be made, especially since, in this case, the copy wouldn't be likely too costly. All together now, the code:

You should get 15.0 returned via the command line in this case. Another thing we can do is:

python argparse_example.py -h

Output:

usage: argparse_example.py [-h] [--x X] [--y Y] [--operation OPERATION]
optional arguments:
-h, --help show this help message and exit
--x X What is the first number?
--y Y What is the second number?
--operation OPERATION
What operation? Can choose add, sub, mul, or div

In the next tutorial, we're going to talk about list comprehension and generators.