2 Using argparse

 

Often getting the right data into your program is a real chore. The argparse module can really make your life much easier by validating and rejecting bad arguments from the user. It’s like our program’s "bouncer," only allowing the right kinds of values into our program. Often half or more of the programs in this book can be handled simply by defining the arguments properly with argparse!

bouncer

In Chapter 1, we ended up writing a very flexible program that could extend warm salutations to an optionally named entity such as the "World" or "Universe":

$ ./hello.py
Hello, World!
$ ./hello.py --name Universe
Hello, Universe!

The program would respond to the -h and --help flags with helpful documentation:

$ ./hello.py -h
usage: hello.py [-h] [-n str]

Say hello

optional arguments:
  -h, --help          show this help message and exit
  -n str, --name str  The name to greet (default: World)

The argparse module helped us define a parser for the parameters and generate the usage, saving us loads of time and making our program look professional. Every program in this book is tested on different inputs, so you’ll really understand how to use this module by the end. I would recommend you look over the documentation (docs.python.org/3/library/argparse.html). Now let’s dig further into what this module can do for us. In this chapter, we will:

2.1  Types of arguments

2.2  Using argparse

2.2.1  Creating the parser

2.2.2  A positional parameter

2.2.3  An optional string parameter

2.2.4  An optional numeric parameter

2.2.5  An optional file parameter

2.2.6  A flag

2.2.7  Returning from get_args

2.2.8  Manually checking arguments

2.3  Examples using argparse

2.3.1  Two different positional arguments

2.3.2  Two of the same positional arguments

2.3.5  File arguments