2

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?

4 Answers 4

8

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)

Sign up to request clarification or add additional context in comments.

1 Comment

It would be nice if you could specify the differences, at least mention that optparsre and getopt are not preferred over argparse.
2

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

Comments

1

You can use getopt with only slight change to your initial plans. It would be like:

python game.py -s127.0.0.1 -nTheKiller1337 

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.