Differences between revisions 4 and 5
Revision 4 as of 2005-01-02 05:27:13
Size: 1017
Editor: aaron
Comment: found it
Revision 5 as of 2005-02-09 21:17:45
Size: 1130
Editor: 168-103-146-113
Comment: +usage string, argument counting to example
Deletions are marked like this. Additions are marked like this.
Line 12: Line 12:
    parser = optparse.OptionParser()     parser = optparse.OptionParser("usage: %prog [options] arg1 arg2")
Line 19: Line 19:
    if len(args) != 2:
        parser.error("incorrect number of arguments")

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", default="127.0.0.1",
   6                        type="string", help = "specify hostname to run on" )
   7     parser.add_option( "-p", "--port", dest="portnum", default=80,
   8                        type="int", help = "port number to run on" )
   9 
  10     (options, args) = parser.parse_args()
  11     if len(args) != 2:
  12         parser.error("incorrect number of arguments")
  13     hostname = options.hostname
  14     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.

OptParse (last edited 2019-09-12 18:41:55 by MatsWichmann)

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