What's the best way to grab/parse command line arguments passed to a Python script?
<p>What's the <strong>easiest, tersest, and most flexible</strong> method or library for parsing Python command line arguments?</p>

<p><strong>This answer suggests <code>optparse</code> which is appropriate for older Python versions. For Python 2.7 and above, <code>argparse</code> replaces <code>optparse</code>. See <a href="http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse">this answer</a> for more information.</strong></p>

<p>As other people pointed out, you are better off going with optparse over getopt.  getopt is pretty much a one-to-one mapping of the standard getopt(3) C library functions, and not very easy to use.</p>

<p>optparse, while being a bit more verbose, is much better structured and simpler to extend later on.</p>

<p>Here's a typical line to add an option to your parser:</p>

<pre><code>parser.add_option('-q', '--query',
            action="store", dest="query",
            help="query string", default="spam")
</code></pre>

<p>It pretty much speaks for itself; at processing time, it will accept -q or --query as options, store the argument in an attribute called query and has a default value if you don't specify it.  It is also self-documenting in that you declare the help argument (which will be used when run with -h/--help) right there with the option.</p>

<p>Usually you parse your arguments with:</p>

<pre><code>options, args = parser.parse_args()
</code></pre>

<p>This will, by default, parse the standard arguments passed to the script (sys.argv[1:])</p>

<p>options.query will then be set to the value you passed to the script.</p>

<p>You create a parser simply by doing</p>

<pre><code>parser = optparse.OptionParser()
</code></pre>

<p>These are all the basics you need.  Here's a complete Python script that shows this:</p>

<pre><code>import optparse

parser = optparse.OptionParser()

parser.add_option('-q', '--query',
    action="store", dest="query",
    help="query string", default="spam")

options, args = parser.parse_args()

print 'Query string:', options.query
</code></pre>

<p>5 lines of python that show you the basics.</p>

<p>Save it in sample.py, and run it once with</p>

<pre><code>python sample.py
</code></pre>

<p>and once with</p>

<pre><code>python sample.py --query myquery
</code></pre>

<p>Beyond that, you will find that optparse is very easy to extend.
In one of my projects, I created a Command class which allows you to nest subcommands in a command tree easily.  It uses optparse heavily to chain commands together.  It's not something I can easily explain in a few lines, but feel free to <a href="https://thomas.apestaart.org/moap/trac/browser/trunk/moap/extern/command/command.py">browse around in my repository</a> for the main class, as well as <a href="https://thomas.apestaart.org/moap/trac/browser/trunk/moap/command/doap.py">a class that uses it and the option parser</a></p>
