Is there a correct way to read the arguments to a python application?
Example:
python game.py -server 127.0.0.1 -nick TheKiller1337
Is there开发者_开发技巧 a correct way of interpreting these argument? As it is now I have a while-loop with some ifs. But it is getting rather large. Should I do a general class for argument reading, or is this already implemented in python?
Use argparse, optparse or getopt.
All three are in the standard library.
I recommend argparse. It is the newest of the three, and is IMO the easiest to use. It was introduced in version 2.7.
If using an older Python version, I would recommend optparse (or get argparse for version 2.5 and 2.6 from pypi)
If you're using v2.7 or newer, you can use argparse
. The documentation has examples.
For earlier Pythons, optparse
is usually the way to go.
The alternative is getopt
, if you're rather be writing 'C'.
For each of these you would have to change your argument list to more conventional. Either of:
python game.py --server 127.0.0.1 --nick TheKiller1337
python game.py -s 127.0.0.1 -n TheKiller1337
You can use getopt with only slight change to your initial plans. It would be like:
python game.py -s127.0.0.1 -nTheKiller1337
I prefer optparse
, because it is supported in 2.6 and because it has a nice interface, automatically generates help texts, and supports additional parameters, not just arguments.
Like this:
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-e", "--event", dest="type", help="type of EVENT")
(options, args) = parser.parse_args()
if options.type == 'fubar':
blah.blubb()
You get the idea.
精彩评论