Differences between revisions 2 and 3
Revision 2 as of 2004-07-19 08:10:14
Size: 844
Editor: dsl254-010-130
Comment: example OptParse use
Revision 3 as of 2005-01-02 05:21:53
Size: 1320
Editor: aaron
Comment: requiring static arguments?
Deletions are marked like this. Additions are marked like this.
Line 24: Line 24:

= 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

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 (last edited 2019-09-12 18:41:55 by MatsWichmann)

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