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:
def calc(x, y, operation): if operation == 'add': return x + y elif operation == 'sub': return x - y elif operation == 'mul': return x * y elif operation == 'div': return x / y operation = calc(7,3,'div') print(operation)
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:
import argparse import sys def main(): parser = argparse.ArgumentParser() parser.add_argument('--x', type=float, default=1.0, help='What is the first number?') parser.add_argument('--y', type=float, default=1.0, help='What is the second number?') parser.add_argument('--operation', type=str, default='add', help='What operation? Can choose add, sub, mul, or div') args = parser.parse_args() sys.stdout.write(str(calc(args)))
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:
def calc(args): if args.operation == 'add': return args.x + args.y elif args.operation == 'sub': return args.x - args.y elif args.operation == 'mul': return args.x * args.y elif args.operation == 'div': return args.x / args.y
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:
import argparse import sys def main(): parser = argparse.ArgumentParser() parser.add_argument('--x', type=float, default=1.0, help='What is the first number?') parser.add_argument('--y', type=float, default=1.0, help='What is the second number?') parser.add_argument('--operation', type=str, default='add', help='What operation? Can choose add, sub, mul, or div') args = parser.parse_args() sys.stdout.write(str(calc(args))) def calc(args): if args.operation == 'add': return args.x + args.y elif args.operation == 'sub': return args.x - args.y elif args.operation == 'mul': return args.x * args.y elif args.operation == 'div': return args.x / args.y if __name__ == '__main__': main()
Now, via the command line, we can do something like:
python argparse_example.py --x=5 --y=3 --operation=mul
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.