844
Comment: example OptParse use
|
1320
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
[http://www.python.org/doc/current/lib/module-optparse.html Official Python 2.3 OptParse Documentation]
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.