Elegant option checking with optparse

A fair amount of the Python code that I write is in the form of scripts designed for command line use. In support of sysadmin activities, data massaging, or other tasks, they often call for options to be passed and parsed. For all but the simplest option setups, the standard-library-included optparse is really the only way to fly. If you are not familiar with its features, I recommend Doug Hellmann’s PyMOTW entry on it.

I had been using optparse to handle the overheard of various option types and formats, parsing these, providing help text and various storage methods for some time. But once I retrieved those options, I often would perform common checks, such as file verification and detecting conflicting parameters, in subsequent loops and functions. As it turns out, the lovely optparse includes a facility to handle this: option callbacks.

Adding callbacks into existing code is fairly simple. Take the code being used to check a given option and pull it out into a function. Then where you define the associated option there are two new parameters to add, “action” and “callback”:

1
2
3
4
5
6
parser = OptionParser(usage=usage)
parser.add_option("-f", "--files", action="callback",
    callback=input_file_handler, type="string",
    help="Comma-separated list of csv file locations \
to combine. Can be specified as full path, or just filenames \
if in current dir."
, dest="csv_files")

Once the option is parsed via

1
(options, args) = parser.parse_args()

the input_file_handler() function would be called. This would be a perfect place to check that the input files passed exist, are files, can be opened, and have content. Each callback is passed the Option instance doing the callback, the option passed, the value passed, and the OptionParser instance doing the parsing.

While the same sort of checks can be performed without callbacks, they provide better isolation of the functions that support a script’s options. This allows for cleaner documentation, debugging and testing of those functions as well as, in many cases, a cleaner main() function.

Post to Twitter Post to Delicious Post to Digg Post to Reddit

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

This entry was posted in CLI, Programming and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>