Python argparse – Fast and Dirty

A lot of tutorials and articles on this subject are wonderful in-depth studies of parsing command line arguments with argparse.  This is not one of them.  This article is aimed at getting us on the ground and running with a common scenario.

Let’s say we want to develop a command line utility to extract data from some data file written by something else in our project. We might start out with a hard coded path to an example data file. But at some point we are going to want to pass in arguments.  The first argument to consider is a path to an arbitrary data file, so we can use our utility without changing code. Next we might want to add a flag to turn on or off behavior.  Let’s say that during the course of development we added a few informational messages. Now we would like to suppress those so that our output can be piped into another command line utility or file.  Finally, maybe we are not happy with the extracted data just going to standard out for piping.  Then we need another optional argument that provides the path to an output file. 

In the end we want something like this:


usage: extract-data [-h] [-q] [-o OUTPUT_FILE] input_file

positional arguments:
input_file Path to data file /path/to/file

optional arguments:
-h, --help show this help message and exit
-q, --quiet suppress messages to stdout
-o OUTPUT_FILE, --output_file OUTPUT_FILE
Path to output file /path/to/file

Setting up these command line arguments in Python with argparse is trivially easy. Below we have a complete program with main function

#!/usr/bin/python3

import argparse


def main():
    # Initialize parser
    parser = argparse.ArgumentParser()

    # positional argument
    parser.add_argument("input_file", help="Path to data file /path/to/file")

    # command line flags
    parser.add_argument("-q", "--quiet", action="store_true",  help="suppress messages to stdout")

    # command line flags with an argument
    parser.add_argument("-o", "--output_file", help="Path to output file /path/to/file")

    # parse args
    args = parser.parse_args()

    # use the option
    if args.input_file:
        print("The input file is: "+args.input_file)
    if args.output_file:
        print("The output file is: "+args.output_file)
    if args.quiet:
        print("Quiet Mode")

    # extract the data ...

if __name__ == "__main__":
    main()

 

For more in-depth examples see