python – optparse

March 11th, 2008 by webstersprodigy

This is a module you can use to parse command line options in python.

Foolishly, I used to do something like:

def getopts(argu):
  opts = {}
  while argu:
    if argu[0][0] == '-':
      opts[argu0]] = argv[1]
      argv = argv[2:]
    else:
      argv = argv[1:]
  return opts

There is a better way, and it’s found in the optparse module.  It is very powerful.  You can easily alias scripts (eg -q is the same as –quiet).  Also, you automatically can add messages to -h or –help, set default values, etc.  A good tutorial on it’s usage is http://docs.python.org/lib/module-optparse.html

Leave a Reply


No computers were harmed in the 0.276 seconds it took to produce this page.