Command-line parsing with Python
February 16, 2008 · Programming
script.py <directive> [args]In python you can use a variety of libraries for command-line parsing like getOpt (oh, yeah again ... i hate getOpt!). My problem was, that i didn't want something complicated, and i hated to write something like:
if param == 'foo': # do foo if param == 'bar': # do barEven with command-line parsing libraries you will eventually do something like that.
So i figured out something like the following. Imagine we have three options (install, delete, help, and update):
class CmdDispatcher: def __init__(self, args): self.__args = args def doInstall(self): # here goes the install option def doUpdate(self): # here goes the update option def doDelete(self): # here goes the delete option def doHelp(self): # here goes the help option # the program starts here def main(): # register actions # initialise the dispatcher and execute cdisp = CmdDispatcher(sys.argv[2:]) try: getattr(cdisp,"do" + sys.argv[1].title())() except (AttributeError, IndexError): cdisp.doHelp()I think the code speaks of itself, you just create an instance of a
CmdDispatcher class and pass all the parameters except the two first (the directive and the script name). Then, by using the getAttr method you call the appropriate method of that instance, constructing its name dynamically from the parameter. If the method does not exist, the doHelp is called.