June 12, 2009

Filed under: Uncategorized — Tags: , , , , , , , — alsuren @ 11:16 pm

Anyone who has ever written a quick-and-dirty demo script in python will probably have found themselves doing something like this at the bottom of their file:

if __name__ == "__main__":
    import sys

(I think everyone has done this at least once, so don’t try to deny it.) This is fine, but kinda screws your user over if they type “ –help”.

What we really want is something that will give us –help functionality, and all of the useful stuff that optparse gives us, without having to jump through the many hoops that optparse makes us jump through. I think it would be enough if we were able to do this at the bottom of our file and get everything to work:

if __name__ == "__main__":
    import commandline

Well it just so happens you can. Just easy_install commandline (if you have setuptools) or go to and download it by hand.

So what run_as_main() does is uses the inspect module to read the function’s docstring, and determine what arguments it takes. It then creates an optparse.OptionParser (using the information gathered from inspect). The OptionParser is then used to read sys.argv (this can be changed by passing an extra argument to run_as_main) and get a list of arguments to pass to the function. It then runs main with the right arguments by doing main(**kwargs).

So how do we use it? Well there is a simple example function included in, defined like this:

def example_function(   string1, 
    """This is just an example. You should really try writing your own
    commandline programs."""
    print string1, string2, int1

If we run it, and ask for help, we get:

$ python commandline/ --help
Usage: commandline/ string1 [string2 [int1]] [Options]

  -h, --help         show this help message and exit
  --string2=STRING2  default="something"
  --int1=INT1        default=1
  --string1=STRING1  This must be specified as an option or argument.

This is just an example. You should really try writing your own commandline

You can clearly see where everything from the function signature is going. I hope you agree that this is a pretty powerful time-saving device. If you have any comments/suggestions, give me a shout.


Blog at