Python Command Line Arguments

For quite some time I have thought I shouldn’t parse my own command line arguments in Python, but each time I looked for the “right” way to do it, I turned back.

Today, I decided to persist.

Now I know why I turned back, the libraries were terrible.

I want to have:

mycleverprog.py mycommand --nifty-option

Where the command is to do one thing or do the opposite.  It is a required thing to say which.

The standard library argparse is a little obscure at first, but with a little reading it starts to make sense.  Cool.

Oh, dang!  It is new in Python 2.7, and I am running 2.6.  Okay, so let’s look at the deprecated optparse, it looks really similar, I’ll convert my embryonic code…

Horrors!  I don’t know the history of the project, but it looks like some “little minds” have been at work on this library.  Because it is called “optparse” it doesn’t support “required options” because the term is self-contradictory.  Come on!  A very common use case is to type a command with a required parameter following on the command line.  Think Unix commands like “rm” or “mkdir” or “touch”, or …, you get the idea.  These commands also have “options” that are optional.  So someone built a library that handles the “options” but makes a point of not handling a required parameter, just because of an unfortunate name for the library!?!  They even waste effort pontificating on why options should be optional?

Bosch!

They do talk about “positional arguments” being required, but it isn’t clear whether they even support that.

My solution?  Download

http://argparse.googlecode.com/files/argparse-1.2.1.tar.gz

put argparse.py in

/usr/local/lib/python2.6/dist-packages

and use argparse.  My little utility will just be for personal use–at least for now. By the time I give it to anyone else, newer versions of Python will be standard.  Or I can include a copy of argparse.py.

-kb, the Kent who is slowly getting better and better at Python.

©2011 Kent Borg


Posted

in

by

Comments

Leave a Reply

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