A better getopt.py

Frank Stajano

This is to announce an unofficial new version of the getopt.py module that helps parsing command line options. I wrote it because it scratched an itch; if it's useful to others too, so much the better.

This is a backwards compatible replacement that does not take away or change any existing functionality. It adds a new function getoptdict() which does the same things as getopt() but returns the result in a dictionary as opposed to a list of pairs. From my humble experience, the caller usually likes random (not sequential) access to the supplied options, so the dictionary appears to be the best match.

The only problem comes up with repeated options (e.g. "-v for verbose, -v -v for very verbose, -v -v -v for really very verbose indeed"). This of course doesn't quite fit in the dictionary model, since each key must be unique. The getoptdict() lets you choose what to do; you can REJECT repeated options (default behaviour) if you abhor them like I do; but you can also APPEND them to a list or KEEP_EARLIEST or KEEP_LATEST.

Another minor update concerns exceptions: the lonely GetoptError has been turned into a small class hierarchy. This allows the caller to distinguish the various errors if fine-grained control is desired. At the same time it is still possible to intercept all errors by simply calling the single GetoptError which is at the root of the hierarchy.

Note that the base file was the getopt.py that came with Python 1.6 alpha 2. Therefore this module won't work with Python < 1.6, because the base file uses 1.6 features such as the index() method for a string.

This modification to getopt.py is released as open source under the same licence as the rest of Python. I, and my employer, disclaim all warranties just like Stichting Mathematisch Centrum and CNRI do. Feedback and bug reports to fstajano@uk.research.att.com.

Download getopt.py

getopt.py 1.3 - Compatible replacement for getopt that returns a dictionary instead of a list of pairs. (29-Jun-2000)


Back to Frank Stajano's home page

CSS Valid HTML 4.0! validated (recheck)