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
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.
In the next post in this series, we will 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.
Was this article useful? Be sure to stay tuned for the next installment and sign up for our Plone & Python How-To digests to receive more how-to guides as soon as they are published!