Thanks for filling out the form! A Six Feet Up representative will be in contact with you soon.

Have a technical question? Ask a Sixie!

<< All Blog Posts
Building Python Command Line Tools, Part 1: ArgParse

Building Python Command Line Tools, Part 1: ArgParse

Over the past few months here at Six Feet Up I have noticed an increasing need to demonstrate the usefulness and efficiency of Python command line tools. Command line tools can be very handy, and, making your own using Python is easier than you might think! The information in this article is part one of our series on building a command line app and will show you how to get started.

The problem: You need to build a quick app to perform an operation in your application

Python makes this very easy to do since it has the "batteries included" to handle parsing command line arguments. Using these tools, we can get started with writing our awesome application to do things like import CSV data into our Pyramid app (or a Django app).

The answer: Use an argument parser to simplify passing arguments

Let's start off with just parsing args from the script so we can pass in the apps config and the CSV file. As of Python 2.7, argparse is now in the standard library. If you are using a version of Python prior to 2.7, you can install it using pip.

Here is the sample code to pass in a couple arguments into our app:

import argparse
import textwrap

def import_sessions():
    description = """\
    Import the session data from a CSV file, given the path.
    """
    parser = argparse.ArgumentParser(
        description=textwrap.dedent(description)
    )
    parser.add_argument('config_uri')
    parser.add_argument('csv_uri')
    options, args = parser.parse_args()

In this first method, we just setup a quick ArgumentParser to read in the command line args. This gives any future users of our script some nice usage instructions and gives our code a clean way to read in our options.

Here is our example running from the command line:

$ bin/import_sessions
usage: import_sessions [-h] config_uri csv_uri
import_sessions: error: too few arguments

And with fancy help:

$ bin/import_sessions -h
usage: import_sessions [-h] config_uri csv_uri

Import the session data from a CSV file, given the path. Example:
'import_sessions etc/paster.ini sessions.csv'

positional arguments:
  config_uri
  csv_uri

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

If you want to get fancier, I'd recommend checking out the Clint command line parser. It will let you do some awesome stuff like put colors, progress bars and unix pipes right in your command line applications.

Next POSTS:

  • Part 2: Console Scripts
    • In the next post in this series, we show you how to use the entry_points in your setup.py to make this into a console script you can use with your Pyramid application.
  • Part 3: Bootstrapping Pyramid
    • In the third post in this series, we put some meat into our script that will actually interact with our Pyramid application. We show bootstrapping the app so we have the full environment ready to use with the database.
  • Part 4: CSV Importing and Time Zones
    • With our application up and running inside our script, we can now manipulate the database and do things like import a CSV file of new data. Our fourth post highlights the strengths of the standard library csv module and show you how to watch out for datetime timezone issues.

Was this series useful? Do you have a topic you'd like to see us write about? Let us know in the comments! Be sure to stay tuned for more Python posts and sign up for our Python How-To digests to receive more how-to guides as soon as they are published!

Strategy Guide Photo

Save Time With Django Strategy Guides

Save time in your Django development projects: download our free strategy guides on Django Filters and Django Tag Templates.

An email will be sent to this address with a link to download the file.