EcStart PHP 技術討論論壇's Archiver

FIEND 發表於 2009-2-26 13:41

getopt – Command line option parsing

<a href="http://docs.python.org/library/getopt.html" target="_blank">http://docs.python.org/library/getopt.html</a>

<br><br><a href="http://www.doughellmann.com/PyMOTW/getopt/index.html" target="_blank">http://www.doughellmann.com/PyMOTW/getopt/index.html</a><br><br><div class="section" id="module-getopt">
<h1>getopt – Command line option parsing<a class="headerlink" href="http://www.doughellmann.com/PyMOTW/getopt/index.html#module-getopt" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" rules="none" frame="void">
<col class="field-name">
<col class="field-body">
<tbody valign="top">
<tr class="field"><th class="field-name">Purpose:</th><td class="field-body">Command line option parsing</td>
</tr>
<tr class="field"><th class="field-name">Python Version:</th><td class="field-body">1.4</td>
</tr>
</tbody>
</table>
<p>The getopt module is the <em>old-school</em> command line option parser which supports
the conventions established by the Unix function getopt(). It parses an
argument sequence, such as sys.argv and returns a sequence of (option,
argument) pairs and a sequence of non-option arguments.</p>
<p>Supported option syntax includes:</p>
<div class="highlight-python"><pre>-a<br>-bval<br>-b val<br>--noarg<br>--witharg=val<br>--witharg val</pre>
</div>
<div class="section" id="function-arguments">
<h2>Function Arguments<a class="headerlink" href="http://www.doughellmann.com/PyMOTW/getopt/index.html#function-arguments" title="Permalink to this headline">¶</a></h2>
<p>The getopt function takes three arguments:</p>
<ul class="simple"><li>The first argument is the sequence of arguments to be parsed. This usually
comes from sys.argv[1:] (ignoring the program name in sys.arg[0]).</li><li>The second argument is the option definition string for single character
options. If one of the options requires an argument, its letter is followed
by a colon.</li><li>The third argument, if used, should be a sequence of the long-style option
names. Long style options can be more than a single character, such as
–noarg or –witharg. The option names in the sequence should not include
the – prefix. If any long option requires an argument, its name should have
a suffix of =.</li></ul>
<p>Short and long form options can be combined in a single call.</p>
</div>
<div class="section" id="short-form-options">
<h2>Short Form Options<a class="headerlink" href="http://www.doughellmann.com/PyMOTW/getopt/index.html#short-form-options" title="Permalink to this headline">¶</a></h2>
<p>If a program wants to take 2 options, -a, and -b with the b option requiring
an argument, the value should be “ab:”.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">getopt</span><br><br><span class="k">print</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">([</span><span class="s">'-a'</span><span class="p">,</span> <span class="s">'-bval'</span><span class="p">,</span> <span class="s">'-c'</span><span class="p">,</span> <span class="s">'val'</span><span class="p">],</span> <span class="s">'ab:c:'</span><span class="p">)</span><br></pre></div>
</div>
<div class="highlight-python"><pre>$ python getopt_short.py<br>([('-a', ''), ('-b', 'val'), ('-c', 'val')], [])</pre>
</div>
</div>
<div class="section" id="long-form-options">
<h2>Long Form Options<a class="headerlink" href="http://www.doughellmann.com/PyMOTW/getopt/index.html#long-form-options" title="Permalink to this headline">¶</a></h2>
<p>If a program wants to take 2 options, –noarg and –witharg the sequence
should be [ ‘noarg’, ‘witharg=’ ].</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">getopt</span><br><br><span class="k">print</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">([</span> <span class="s">'--noarg'</span><span class="p">,</span> <span class="s">'--witharg'</span><span class="p">,</span> <span class="s">'val'</span><span class="p">,</span> <span class="s">'--witharg2=another'</span> <span class="p">],</span><br>                    <span class="s">''</span><span class="p">,</span><br>                    <span class="p">[</span> <span class="s">'noarg'</span><span class="p">,</span> <span class="s">'witharg='</span><span class="p">,</span> <span class="s">'witharg2='</span> <span class="p">])</span><br></pre></div>
</div>
<div class="highlight-python"><pre>$ python getopt_long.py<br>([('--noarg', ''), ('--witharg', 'val'), ('--witharg2', 'another')], [])</pre>
</div>
</div>
<div class="section" id="example">
<h2>Example<a class="headerlink" href="http://www.doughellmann.com/PyMOTW/getopt/index.html#example" title="Permalink to this headline">¶</a></h2>
<p>Below is a more complete example program which takes 5 options: -o, -v,
–output, –verbose, and –version. The -o, –output, and –version options
require an argument.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">getopt</span><br><span class="k">import</span> <span class="nn">sys</span><br><br><span class="n">version</span> <span class="o">=</span> <span class="s">'1.0'</span><br><span class="n">verbose</span> <span class="o">=</span> <span class="bp">False</span><br><span class="n">output_filename</span> <span class="o">=</span> <span class="s">'default.out'</span><br><br><span class="k">print</span> <span class="s">'ARGV      :'</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">:]</span><br><br><span class="n">options</span><span class="p">,</span> <span class="n">remainder</span> <span class="o">=</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">:],</span> <span class="s">'o:v'</span><span class="p">,</span> <span class="p">[</span><span class="s">'output='</span><span class="p">,</span> <br>                                                         <span class="s">'verbose'</span><span class="p">,</span><br>                                                         <span class="s">'version='</span><span class="p">,</span><br>                                                         <span class="p">])</span><br><span class="k">print</span> <span class="s">'OPTIONS   :'</span><span class="p">,</span> <span class="n">options</span><br><br><span class="k">for</span> <span class="n">opt</span><span class="p">,</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">options</span><span class="p">:</span><br>    <span class="k">if</span> <span class="n">opt</span> <span class="ow">in</span> <span class="p">(</span><span class="s">'-o'</span><span class="p">,</span> <span class="s">'--output'</span><span class="p">):</span><br>        <span class="n">output_filename</span> <span class="o">=</span> <span class="n">arg</span><br>    <span class="k">elif</span> <span class="n">opt</span> <span class="ow">in</span> <span class="p">(</span><span class="s">'-v'</span><span class="p">,</span> <span class="s">'--verbose'</span><span class="p">):</span><br>        <span class="n">verbose</span> <span class="o">=</span> <span class="bp">True</span><br>    <span class="k">elif</span> <span class="n">opt</span> <span class="o">==</span> <span class="s">'--version'</span><span class="p">:</span><br>        <span class="n">version</span> <span class="o">=</span> <span class="n">arg</span><br><br><span class="k">print</span> <span class="s">'VERSION   :'</span><span class="p">,</span> <span class="n">version</span><br><span class="k">print</span> <span class="s">'VERBOSE   :'</span><span class="p">,</span> <span class="n">verbose</span><br><span class="k">print</span> <span class="s">'OUTPUT    :'</span><span class="p">,</span> <span class="n">output_filename</span><br><span class="k">print</span> <span class="s">'REMAINING :'</span><span class="p">,</span> <span class="n">remainder</span><br></pre></div>
</div>
<p>The program can be called in a variety of ways.</p>
<div class="highlight-python"><pre>$ python getopt_example.py<br>ARGV      : []<br>OPTIONS   : []<br>VERSION   : 1.0<br>VERBOSE   : False<br>OUTPUT    : default.out<br>REMAINING : []</pre>
</div>
<p>A single letter option can be a separate from its argument:</p>
<div class="highlight-python"><pre>$ python getopt_example.py -o foo<br>ARGV      : ['-o', 'foo']<br>OPTIONS   : [('-o', 'foo')]<br>VERSION   : 1.0<br>VERBOSE   : False<br>OUTPUT    : foo<br>REMAINING : []</pre>
</div>
<p>or combined:</p>
<div class="highlight-python"><pre>$ python getopt_example.py -ofoo<br>ARGV      : ['-ofoo']<br>OPTIONS   : [('-o', 'foo')]<br>VERSION   : 1.0<br>VERBOSE   : False<br>OUTPUT    : foo<br>REMAINING : []</pre>
</div>
<p>A long form option can similarly be separate:</p>
<div class="highlight-python"><pre>$ python getopt_example.py --output foo<br>ARGV      : ['--output', 'foo']<br>OPTIONS   : [('--output', 'foo')]<br>VERSION   : 1.0<br>VERBOSE   : False<br>OUTPUT    : foo<br>REMAINING : []</pre>
</div>
<p>or combined, with =:</p>
<div class="highlight-python"><pre>$ python getopt_example.py --output=foo<br>ARGV      : ['--output=foo']<br>OPTIONS   : [('--output', 'foo')]<br>VERSION   : 1.0<br>VERBOSE   : False<br>OUTPUT    : foo<br>REMAINING : []</pre>
</div>
</div>
<div class="section" id="abbreviating-long-form-options">
<h2>Abbreviating Long Form Options<a class="headerlink" href="http://www.doughellmann.com/PyMOTW/getopt/index.html#abbreviating-long-form-options" title="Permalink to this headline">¶</a></h2>
<p>The long form option does not have to be spelled out entirely, so long as a
unique prefix is provided:</p>
<div class="highlight-python"><pre>$ python getopt_example.py --o foo<br>ARGV      : ['--o', 'foo']<br>OPTIONS   : [('--output', 'foo')]<br>VERSION   : 1.0<br>VERBOSE   : False<br>OUTPUT    : foo<br>REMAINING : []</pre>
</div>
<p>If a unique prefix is not provided, an exception is raised.</p>
<div class="highlight-python"><pre>$ python getopt_example.py --ver 2.0<br>ARGV      : ['--ver', '2.0']<br>Traceback (most recent call last):<br>  File "getopt_example.py", line 44, in &lt;module&gt;<br>    'version=',<br>  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/getopt.py", line 89, in getopt<br>    opts, args = do_longs(opts, args[0][2:], longopts, args[1:])<br>  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/getopt.py", line 153, in do_longs<br>    has_arg, opt = long_has_args(opt, longopts)<br>  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/getopt.py", line 180, in long_has_args<br>    raise GetoptError('option --%s not a unique prefix' % opt, opt)<br>getopt.GetoptError: option --ver not a unique prefix</pre>
</div>
<p>Option processing stops as soon as the first non-option argument is
encountered.</p>
<div class="highlight-python"><pre>$ python getopt_example.py -v not_an_option --output foo<br>ARGV      : ['-v', 'not_an_option', '--output', 'foo']<br>OPTIONS   : [('-v', '')]<br>VERSION   : 1.0<br>VERBOSE   : True<br>OUTPUT    : default.out<br>REMAINING : ['not_an_option', '--output', 'foo']</pre>
</div>
</div>
<div class="section" id="gnu-style-option-parsing">
<h2>GNU-style Option Parsing<a class="headerlink" href="http://www.doughellmann.com/PyMOTW/getopt/index.html#gnu-style-option-parsing" title="Permalink to this headline">¶</a></h2>
<p>New in Python 2.3, an additional function gnu_getopt() was added. It allows
option and non-option arguments to be mixed on the command line in any order.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="k">import</span> <span class="nn">getopt</span><br><span class="k">import</span> <span class="nn">sys</span><br><br><span class="n">version</span> <span class="o">=</span> <span class="s">'1.0'</span><br><span class="n">verbose</span> <span class="o">=</span> <span class="bp">False</span><br><span class="n">output_filename</span> <span class="o">=</span> <span class="s">'default.out'</span><br><br><span class="k">print</span> <span class="s">'ARGV      :'</span><span class="p">,</span> <span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">:]</span><br><br><span class="n">options</span><span class="p">,</span> <span class="n">remainder</span> <span class="o">=</span> <span class="n">getopt</span><span class="o">.</span><span class="n">gnu_getopt</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">:],</span> <span class="s">'o:v'</span><span class="p">,</span> <span class="p">[</span><span class="s">'output='</span><span class="p">,</span> <br>                                                             <span class="s">'verbose'</span><span class="p">,</span><br>                                                             <span class="s">'version='</span><span class="p">,</span><br>                                                             <span class="p">])</span><br><span class="k">print</span> <span class="s">'OPTIONS   :'</span><span class="p">,</span> <span class="n">options</span><br><br><span class="k">for</span> <span class="n">opt</span><span class="p">,</span> <span class="n">arg</span> <span class="ow">in</span> <span class="n">options</span><span class="p">:</span><br>    <span class="k">if</span> <span class="n">opt</span> <span class="ow">in</span> <span class="p">(</span><span class="s">'-o'</span><span class="p">,</span> <span class="s">'--output'</span><span class="p">):</span><br>        <span class="n">output_filename</span> <span class="o">=</span> <span class="n">arg</span><br>    <span class="k">elif</span> <span class="n">opt</span> <span class="ow">in</span> <span class="p">(</span><span class="s">'-v'</span><span class="p">,</span> <span class="s">'--verbose'</span><span class="p">):</span><br>        <span class="n">verbose</span> <span class="o">=</span> <span class="bp">True</span><br>    <span class="k">elif</span> <span class="n">opt</span> <span class="o">==</span> <span class="s">'--version'</span><span class="p">:</span><br>        <span class="n">version</span> <span class="o">=</span> <span class="n">arg</span><br><br><span class="k">print</span> <span class="s">'VERSION   :'</span><span class="p">,</span> <span class="n">version</span><br><span class="k">print</span> <span class="s">'VERBOSE   :'</span><span class="p">,</span> <span class="n">verbose</span><br><span class="k">print</span> <span class="s">'OUTPUT    :'</span><span class="p">,</span> <span class="n">output_filename</span><br><span class="k">print</span> <span class="s">'REMAINING :'</span><span class="p">,</span> <span class="n">remainder</span><br></pre></div>
</div>
<p>After changing the call in the previous example, the difference becomes clear:</p>
<div class="highlight-python"><pre>$ python getopt_gnu.py -v not_an_option --output foo<br>ARGV      : ['-v', 'not_an_option', '--output', 'foo']<br>OPTIONS   : [('-v', ''), ('--output', 'foo')]<br>VERSION   : 1.0<br>VERBOSE   : True<br>OUTPUT    : foo<br>REMAINING : ['not_an_option']</pre>
</div>
</div>
<div class="section" id="special-case">
<h2>Special Case: <tt class="docutils literal"><span class="pre">--</span></tt><a class="headerlink" href="http://www.doughellmann.com/PyMOTW/getopt/index.html#special-case" title="Permalink to this headline">¶</a></h2>
<p>If getopt encounters <tt class="docutils literal"><span class="pre">--</span></tt> in the input arguments, it stops processing the remaining arguments as options.</p>
<div class="highlight-python"><pre>$ python getopt_example.py -v -- --output foo<br>ARGV      : ['-v', '--', '--output', 'foo']<br>OPTIONS   : [('-v', '')]<br>VERSION   : 1.0<br>VERBOSE   : True<br>OUTPUT    : default.out<br>REMAINING : ['--output', 'foo']</pre>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils"><dt><a class="reference external" href="http://docs.python.org/library/getopt.html">getopt</a></dt><dd>The standard library documentation for this module.</dd><dt><a title="Command line option parser to replace getopt." class="reference external" href="http://www.doughellmann.com/PyMOTW/optparse/index.html#module-optparse"><tt class="xref docutils literal"><span class="pre">optparse</span></tt></a></dt><dd>The <a title="Command line option parser to replace getopt." class="reference external" href="http://www.doughellmann.com/PyMOTW/optparse/index.html#module-optparse"><tt class="xref docutils literal"><span class="pre">optparse</span></tt></a> module.</dd></dl>
</div>
</div>
</div><br>

頁: [1]

Powered by Discuz! Archiver 7.2  © 2001-2009 Comsenz Inc.