Differences between revisions 3 and 4
Revision 3 as of 2005-01-02 05:21:53
Size: 1320
Editor: aaron
Comment: requiring static arguments?
Revision 4 as of 2005-01-02 05:27:13
Size: 1017
Editor: aaron
Comment: found it
Deletions are marked like this. Additions are marked like this.
Line 23: Line 23:
''args'' contains your fixed arguments, ''options'' contains your values.

For example, {{{options.portnum}}} would contain the integer {{{80}}}, in the example above.
Line 24: Line 28:

= Discussion =

I'm having difficulty figuring out the recommended way of requring static arguments. (The documentation seems religiously against the idea.)

I'd just use argv, but it seems unPythonic: I need to first determine if the first word used was the name of the program, "python2.3", "python", or whatever else they could have typed beforehand.

I'd like optparse to just do it for me, if at all possible.

-- LionKimbro [[DateTime(2005-01-02T05:21:52Z)]]

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()
   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     hostname = options.hostname
  12     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.