This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

argparse

Never fear - argparse is here to the rescue you from your sys.argv woes!

The argparse module helps you deal with parsing and validating command line arguments, so that you can concentrate on things that matter!

Here is our calculator program again, this time with argparse handling all the boring bits.

import argparse

def calculate(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

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Best calculator in the world")
    parser.add_argument("x", type=int)
    parser.add_argument("y", type=int)
    parser.add_argument("operation", choices=['add', 'sub', 'mul', 'div'])

    # parse the command line arguments
    args = parser.parse_args()
    print(type(args))
    print(args)
 
    print(calculate(args.x, args.y, args.operation))

I would assume that you can easily understand the program above just by reading it.

If you try running the following, you will get a helpful guide on how to use your program, all generated automatically with minimal effort from you. Anything in [ square brackets ] mean that they are optional.

$ python3 calculator.py --help
usage: calculator.py [-h] x y {add,sub,mul,div}

Best calculator in the world

positional arguments:
  x
  y
  {add,sub,mul,div}

optional arguments:
  -h, --help         show this help message and exit

As the help says, you can also run python3 calculator.py -h to get the same guide.

Now if you run your program with valid command line arguments, you will get the program executing correctly.

$ python3 calculator.py 7 3 sub
<class 'argparse.Namespace'>
Namespace(operation='sub', x=7, y=3)
4

As you can see in our code, we created an instance of ArgumentParser and called it parser.

parser.parse_args() returns an instance of argparse.Namespace, which has the attributes x, y, operation which we declared as arguments using parser.add_argument() earlier.

We then use these attributes as arguments to the function call calculate().

Now, try being a naughty user and enter all possible bad inputs you can think of. Check out what happens! What error messages do you get?

$ python3 calculator.py
$ python3 calculator.py 3+5
$ python3 calculator.py 3 5
$ python3 calculator.py add 4
$ python3 calculator.py 2
$ python3 calculator.py 5 2 and
$ python3 calculator.py 1 infinity
$ python3 calculator.py 4 8 6
$ python3 calculator.py a - b
$ python3 calculator.py not another lockdown
$ python3 calculator.py 1 2 3 4 5 6 7 8
$ python3 calculator.py 1 2 add 4 5 6 7 8
$ python3 calculator.py girls just wanna have fun!!!

Ah… much better! No more headaches from dealing with naughty users! Thank you argparse!