One of the most often read postings on this blog is the one about my getopts-enabled shell script template. So I figured, a similar template in Python would also be useful. Like the shell script, it’s quite trivial, but it might still save some time.
The template is an example for a typical unix utility. It connects two aspects: An optparse-based command line parser and iterating over multiple input sources using the fileinput module.
I’ve used command line parsers in several programming languages, but from all of them, I liked Python’s optparse
module best (for those who need it, Python’s standard library still provides a classic getopt). The fileinput
module is simple but useful. Beyond its main functionality, it supports more advanced features like transparent decompressing (not really Unix-like though) and in-place filtering of files, but I rarely ever use them.
Here’s the template for download.
While I use Python quite often (for small scripts etc.), I must say that I really like the option parser for Java I once wrote best:
http://twoday.tuwien.ac.at/pub/stories/305002/
It uses annotations and is very declarative. It has lots of options, but they all default to something so you do not need to define anything (other than what is an option). It can parse a lot of types builtin and is extensible for not builtin supported types.
I really like it, but I never had any real life use for it (SWING apps usually don’t need sophisticated command line arguments, neither do webapps). :(
Looks interesting! Python has annotations, too, but they aren’t as ubiquitously used as in Java.
Maybe you should publish your command line parser on Google Code or on Bitbucket so that others can find it more easily. I’ve written a few command line tools in Java, but I’ve never been happy with commons-cli.