Revision 10 as of 2005-12-02 23:34:04

Clear message

OptParse is a module introduced in Python2.3 that makes it easy to write command line tools.

You give a description of the options that the program can receive, and OptParse will do reasonable stuff for you.

For example:

   1 import optparse
   2 
   3 if __name__=="__main__":
   4     parser = optparse.OptionParser("usage: %prog [options] arg1 arg2")
   5     parser.add_option("-H", "--host", dest="hostname",
   6                       default="127.0.0.1", type="string",
   7                       help="specify hostname to run on")
   8     parser.add_option("-p", "--port", dest="portnum", default=80,
   9                       type="int", help="port number to run on")
  10 
  11     (options, args) = parser.parse_args()
  12     if len(args) != 2:
  13         parser.error("incorrect number of arguments")
  14     hostname = options.hostname
  15     portnum = options.portnum

args contains your fixed arguments, options contains your values.

For example, options.portnum would contain the integer 80, in the example above.

References

Discussion

* Impossible to verify the amount of options passed.

I have had to create a function to verify in certain circumstances if we have at least one option set:

(takes an OptParse Values instances returned by parser.parse_args() as argument)

   1 def is_empty(options):                                                                                                                                                   
   2     """
   3     Returns True or False if an option is set or not.
   4     """
   5     values = options.__dict__.values()                                                                                                                                   
   6     return (values == [None] * len(values))

Is my need for this is due to a bad design in my option parsing?

- NicolasCouture Mon Nov 28 18:08:12 EST 2005

You're trying to see if any options have been set?

Hmm... Maybe what you really want is an argument?

Otherwise, I don't have an answer for you; I don't think it keeps a count of how many options it has seen.

-- LionKimbro DateTime(2005-12-02T23:34:02Z)

Unable to edit the page? See the FrontPage for instructions.