summaryrefslogtreecommitdiff
path: root/doc/argparse-vs-optparse.html
blob: 54f40aa580608ad943bf7983eb690afdc3696b83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>argparse vs. optparse &mdash; argparse v1.0 documentation</title>
    <link rel="stylesheet" href="_static/default.css" type="text/css" />
    <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '',
        VERSION:     '1.0',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="_static/jquery.js"></script>
    <script type="text/javascript" src="_static/doctools.js"></script>
    <link rel="top" title="argparse v1.0 documentation" href="index.html" />
    <link rel="next" title="API documentation" href="api-docs.html" />
    <link rel="prev" title="Introduction to argparse" href="overview.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="api-docs.html" title="API documentation"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="overview.html" title="Introduction to argparse"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">argparse v1.0 documentation</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="argparse-vs-optparse">
<span id="id1"></span><h1>argparse vs. optparse<a class="headerlink" href="#argparse-vs-optparse" title="Permalink to this headline">¶</a></h1>
<p>The optparse module already comes in the Python standard library. So why would you want to use argparse instead? Here&#8217;s a few of the many reasons:</p>
<ul class="simple">
<li>The argparse module can handle positional and optional arguments, while optparse can handle only optional arguments. (See <a title="add_argument" class="reference external" href="add_argument.html#add_argument"><tt class="xref docutils literal"><span class="pre">add_argument()</span></tt></a>.)</li>
<li>The argparse module isn&#8217;t dogmatic about what your command line interface should look like - options like <tt class="docutils literal"><span class="pre">-file</span></tt> or <tt class="docutils literal"><span class="pre">/file</span></tt> are supported, as are required options. Optparse refuses to support these features, preferring purity over practicality.</li>
<li>The argparse module produces more informative usage messages, including command-line usage determined from your arguments, and help messages for both positional and optional arguments. The optparse module requires you to write your own usage string, and has no way to display help for positional arguments.</li>
<li>The argparse module supports action that consume a variable number of command-line args, while optparse requires that the exact number of arguments (e.g. 1, 2, or 3) be known in advance.  (See <a title="add_argument" class="reference external" href="add_argument.html#add_argument"><tt class="xref docutils literal"><span class="pre">add_argument()</span></tt></a>.)</li>
<li>The argparse module supports parsers that dispatch to sub-commands, while optparse requires setting <tt class="docutils literal"><span class="pre">allow_interspersed_args</span></tt> and doing the parser dispatch manually. (See <a title="add_subparsers" class="reference external" href="other-methods.html#add_subparsers"><tt class="xref docutils literal"><span class="pre">add_subparsers()</span></tt></a>.)</li>
<li>The argparse module allows the <tt class="docutils literal"><span class="pre">type</span></tt> and <tt class="docutils literal"><span class="pre">action</span></tt> parameters to <a title="add_argument" class="reference external" href="add_argument.html#add_argument"><tt class="xref docutils literal"><span class="pre">add_argument()</span></tt></a> to be specified with simple callables, while optparse requires hacking class attributes like <tt class="docutils literal"><span class="pre">STORE_ACTIONS</span></tt> or <tt class="docutils literal"><span class="pre">CHECK_METHODS</span></tt> to get proper argument checking. (See <a title="add_argument" class="reference external" href="add_argument.html#add_argument"><tt class="xref docutils literal"><span class="pre">add_argument()</span></tt></a>).</li>
</ul>
<p>The following sections discuss some of these points and a few of the other advantages of the argparse module.</p>
<div class="section" id="advantages-of-argparse">
<h2>Advantages of argparse<a class="headerlink" href="#advantages-of-argparse" title="Permalink to this headline">¶</a></h2>
<div class="section" id="positional-arguments">
<h3>Positional arguments<a class="headerlink" href="#positional-arguments" title="Permalink to this headline">¶</a></h3>
<p>The argparse module supports optional and positional arguments in a manner similar to the optparse module:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">argparse</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;--foo&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&#39;optional foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;bar&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&#39;positional bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;--foo spam badger&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span><span class="o">.</span><span class="n">foo</span>
<span class="go">&#39;spam&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">values</span><span class="o">.</span><span class="n">bar</span>
<span class="go">&#39;badger&#39;</span>
</pre></div>
</div>
<p>Some of the important differences illustrated here:</p>
<ul class="simple">
<li>ArgumentParser objects use an <a title="add_argument" class="reference external" href="add_argument.html#add_argument"><tt class="xref docutils literal"><span class="pre">add_argument()</span></tt></a> method instead of <tt class="docutils literal"><span class="pre">add_option</span></tt>. The APIs are quite similar to the optparse ones, and support the keyword arguments <tt class="docutils literal"><span class="pre">action</span></tt>, <tt class="docutils literal"><span class="pre">dest</span></tt>, <tt class="docutils literal"><span class="pre">nargs</span></tt>, <tt class="docutils literal"><span class="pre">const</span></tt>, <tt class="docutils literal"><span class="pre">default</span></tt>, <tt class="docutils literal"><span class="pre">type</span></tt>, <tt class="docutils literal"><span class="pre">choices</span></tt>, <tt class="docutils literal"><span class="pre">help</span></tt> and <tt class="docutils literal"><span class="pre">metavar</span></tt> in much the same way that optparse does (with differences noted below).</li>
<li>The <a title="parse_args" class="reference external" href="parse_args.html#parse_args"><tt class="xref docutils literal"><span class="pre">parse_args()</span></tt></a> method returns a single namespace object, not a <tt class="docutils literal"><span class="pre">(namespace,</span> <span class="pre">remaining_args)</span></tt> pair. What used to be remaining arguments with optparse are now taken care of by argparse&#8217;s positional arguments.</li>
</ul>
</div>
<div class="section" id="optional-arguments">
<h3>Optional arguments<a class="headerlink" href="#optional-arguments" title="Permalink to this headline">¶</a></h3>
<p>The argparse module doesn&#8217;t try to dictate what your command line interface should look like. You want single dashes but long option names? Sure! You want to use <tt class="docutils literal"><span class="pre">'+'</span></tt> as a flag character? Sure! You want required options? Sure!</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s">&#39;PROG&#39;</span><span class="p">,</span> <span class="n">prefix_chars</span><span class="o">=</span><span class="s">&#39;-+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;+bar&#39;</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;-foo 1 +bar 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;2&#39;, foo=&#39;1&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;-foo X&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">usage: PROG [-h] [-foo FOO] +bar BAR</span>
<span class="go">PROG: error: argument +bar is required</span>
</pre></div>
</div>
</div>
<div class="section" id="generated-usage">
<h3>Generated usage<a class="headerlink" href="#generated-usage" title="Permalink to this headline">¶</a></h3>
<p>With optparse, if you don&#8217;t supply a usage string, you typically end up with <tt class="docutils literal"><span class="pre">&quot;PROG</span> <span class="pre">[options]&quot;</span></tt> displayed for usage. Since the ArgumentParser objects know both your optional and positional arguments, if you don&#8217;t supply your own usage string, a reasonable one will be derived for you:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-w&#39;</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="s">&#39;123&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&#39;w help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-x&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">&#39;+&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&#39;x help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;y&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">&#39;?&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&#39;y help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;z&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">&#39;*&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="s">&#39;z help&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;-x 2 3 -w 1 a b c d&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(w=&#39;1&#39;, x=[&#39;2&#39;, &#39;3&#39;], y=&#39;a&#39;, z=[&#39;b&#39;, &#39;c&#39;, &#39;d&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [-w {1,2,3}] [-x X [X ...]] [y] [z [z ...]]</span>

<span class="go">positional arguments:</span>
<span class="go">  y             y help</span>
<span class="go">  z             z help</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help    show this help message and exit</span>
<span class="go">  -w {1,2,3}    w help</span>
<span class="go">  -x X [X ...]  x help</span>
</pre></div>
</div>
</div>
<div class="section" id="more-nargs-options">
<h3>More nargs options<a class="headerlink" href="#more-nargs-options" title="Permalink to this headline">¶</a></h3>
<p>As you may have noticed in the previous section, the argparse module adds a number of useful new specifiers for the <tt class="docutils literal"><span class="pre">nargs</span></tt> keyword argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-x&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">&#39;?&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="s">&#39;X&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-y&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">&#39;+&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;z&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">&#39;*&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;-y 0.5 -x&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(x=&#39;X&#39;, y=[&#39;0.5&#39;], z=[])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;-y 0.5 -xA 0 1 1 0&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(x=&#39;A&#39;, y=[&#39;0.5&#39;], z=[&#39;0&#39;, &#39;1&#39;, &#39;1&#39;, &#39;0&#39;])</span>
</pre></div>
</div>
<p>In particular argparse supports:</p>
<ul class="simple">
<li><tt class="docutils literal"><span class="pre">N</span></tt> (an integer) meaning that <tt class="docutils literal"><span class="pre">N</span></tt> string args are allowed.</li>
<li>A <tt class="docutils literal"><span class="pre">'?'</span></tt>, meaning that zero or one string args are allowed.</li>
<li>A <tt class="docutils literal"><span class="pre">'*'</span></tt>, meaning that zero or more string args are allowed.</li>
<li>A <tt class="docutils literal"><span class="pre">'+'</span></tt>, meaning that one or more string args are allowed.</li>
</ul>
<p>By default, a single argument is accepted. For everything but <tt class="docutils literal"><span class="pre">'?'</span></tt> and the default, a list of values will be produced instead of single value.</p>
</div>
<div class="section" id="sub-commands">
<h3>Sub-commands<a class="headerlink" href="#sub-commands" title="Permalink to this headline">¶</a></h3>
<p>With optparse, dispatching to subparsers required disallowing interspersed args and then manually matching arg names to parsers. With the argparse module, sub-parsers are supported through the <a title="add_subparsers" class="reference external" href="other-methods.html#add_subparsers"><tt class="xref docutils literal"><span class="pre">add_subparsers()</span></tt></a> method. The <a title="add_subparsers" class="reference external" href="other-methods.html#add_subparsers"><tt class="xref docutils literal"><span class="pre">add_subparsers()</span></tt></a> method creates and returns a positional argument that exposes an <tt class="docutils literal"><span class="pre">add_parser</span></tt> method from which new named parsers can be created:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="c"># create the base parser with a subparsers argument</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;--bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">subparsers</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">add_subparsers</span><span class="p">()</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># add a sub-command &quot;abc&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_abc</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s">&#39;abc&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_abc</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-a&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;store_true&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_abc</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;--b&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_abc</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;c&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="mf">2</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># add a sub-command &quot;xyz&quot;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_xyz</span> <span class="o">=</span> <span class="n">subparsers</span><span class="o">.</span><span class="n">add_parser</span><span class="p">(</span><span class="s">&#39;xyz&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_xyz</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;--x&#39;</span><span class="p">,</span> <span class="n">dest</span><span class="o">=</span><span class="s">&#39;xxx&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_xyz</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-y&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="s">&#39;store_const&#39;</span><span class="p">,</span> <span class="n">const</span><span class="o">=</span><span class="nb">object</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser_xyz</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;z&#39;</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="s">&#39;123&#39;</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c"># parse, using the subcommands</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;abc --b 2 AA BB&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(a=None, b=2, bar=None, c=[&#39;AA&#39;, &#39;BB&#39;])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;--bar B xyz -y 3&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;B&#39;, xxx=None, y=&lt;type &#39;object&#39;&gt;, z=&#39;3&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;xyz --b 42&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">usage: PROG xyz [-h] [--x XXX] [-y] {1,2,3}</span>
<span class="go">PROG xyz: error: no such option: --b</span>
</pre></div>
</div>
<p>Note that in addition to all the usual arguments that are valid to the <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> constructor, the <tt class="docutils literal"><span class="pre">add_parser</span></tt> method of a sub-parsers argument requires a name for the parser.  This is used to determine which parser is invoked at argument parsing time, and to print a more informative usage message.</p>
</div>
<div class="section" id="callable-types">
<h3>Callable types<a class="headerlink" href="#callable-types" title="Permalink to this headline">¶</a></h3>
<p>The argparse module allows any callable that takes a single string argument as the value for the <tt class="docutils literal"><span class="pre">type</span></tt> keyword argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;x&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">float</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;y&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">complex</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;z&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">file</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;0.625 4j argparse.py&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(x=0.625, y=4j, z=&lt;open file &#39;argparse.py&#39;, mode &#39;r&#39; at 0x...&gt;)</span>
</pre></div>
</div>
<p>For most users, you&#8217;ll never need to specify a type in string form again.</p>
</div>
<div class="section" id="extensible-actions">
<h3>Extensible actions<a class="headerlink" href="#extensible-actions" title="Permalink to this headline">¶</a></h3>
<p>The argparse module allows a more easily extensible means of providing new types of parsing actions. The easiest way of generating such a new action is to extend <tt class="docutils literal"><span class="pre">argparse.Action</span></tt> and override the <tt class="docutils literal"><span class="pre">__init__()</span></tt> and <tt class="docutils literal"><span class="pre">__call__()</span></tt> methods as necessary:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">FooAction</span><span class="p">(</span><span class="n">argparse</span><span class="o">.</span><span class="n">Action</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">foo</span><span class="p">,</span> <span class="o">**</span><span class="n">kwargs</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">super</span><span class="p">(</span><span class="n">FooAction</span><span class="p">,</span> <span class="bp">self</span><span class="p">)</span><span class="o">.</span><span class="n">__init__</span><span class="p">(</span><span class="o">**</span><span class="n">kwargs</span><span class="p">)</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">foo</span> <span class="o">=</span> <span class="n">foo</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="nf">__call__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">parser</span><span class="p">,</span> <span class="n">namespace</span><span class="p">,</span> <span class="n">value</span><span class="p">,</span> <span class="n">option_string</span><span class="o">=</span><span class="bp">None</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">setattr</span><span class="p">(</span><span class="n">namespace</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">dest</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">foo</span> <span class="o">%</span> <span class="n">value</span><span class="p">)</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-x&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="n">FooAction</span><span class="p">,</span> <span class="n">foo</span><span class="o">=</span><span class="s">&#39;xfoox(</span><span class="si">%s</span><span class="s">)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;y&#39;</span><span class="p">,</span> <span class="n">action</span><span class="o">=</span><span class="n">FooAction</span><span class="p">,</span> <span class="n">foo</span><span class="o">=</span><span class="s">&#39;fyoyo(</span><span class="si">%s</span><span class="s">)&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;42&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(x=None, y=&#39;fyoyo(42)&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;42 -x 0&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(x=&#39;xfoox(0)&#39;, y=&#39;fyoyo(42)&#39;)</span>
</pre></div>
</div>
<p>The ArgumentParser constructs your action object when <a title="add_argument" class="reference external" href="add_argument.html#add_argument"><tt class="xref docutils literal"><span class="pre">add_argument()</span></tt></a> is called, and passes on the arguments it received. Thus if you need more than the usual <tt class="docutils literal"><span class="pre">dest</span></tt>, <tt class="docutils literal"><span class="pre">nargs</span></tt>, etc., simply declare it in your <tt class="docutils literal"><span class="pre">__init__()</span></tt> method and provide a value for it in the corresponding call.</p>
</div>
<div class="section" id="more-choices">
<h3>More choices<a class="headerlink" href="#more-choices" title="Permalink to this headline">¶</a></h3>
<p>In optparse, the <tt class="docutils literal"><span class="pre">choices</span></tt> keyword argument accepts only a list of strings. The argparse module allows <tt class="docutils literal"><span class="pre">choices</span></tt> to provide any container object, and tests the arg string values against this container after they have been type-converted:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-x&#39;</span><span class="p">,</span> <span class="n">nargs</span><span class="o">=</span><span class="s">&#39;+&#39;</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="s">&#39;abc&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-y&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="nb">xrange</span><span class="p">(</span><span class="mf">3</span><span class="p">))</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;z&#39;</span><span class="p">,</span> <span class="nb">type</span><span class="o">=</span><span class="nb">float</span><span class="p">,</span> <span class="n">choices</span><span class="o">=</span><span class="p">[</span><span class="mf">0.5</span><span class="p">,</span> <span class="mf">1.5</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;-x a c -y 2 0.5&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(x=[&#39;a&#39;, &#39;c&#39;], y=2, z=0.5)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;1.0&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">usage: PROG [-h] [-x {a,b,c} [{a,b,c} ...]] [-y {0,1,2}] {0.5,1.5}</span>
<span class="go">PROG: error: argument z: invalid choice: 1.0 (choose from 0.5, 1.5)</span>
</pre></div>
</div>
<p>Note that if choices is supplied for an argument that consumes multiple arg strings, each arg string will be checked against those choices.</p>
</div>
<div class="section" id="sharing-arguments">
<h3>Sharing arguments<a class="headerlink" href="#sharing-arguments" title="Permalink to this headline">¶</a></h3>
<p>The argparse module allows you to construct simple inheritance hierarchies of parsers when it&#8217;s convenient to have multiple parsers that share some of the same arguments:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">foo_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">add_help</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;--foo&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">add_help</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">bar_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;bar&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_bar_baz_parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span>
<span class="gp">... </span>    <span class="n">parents</span><span class="o">=</span><span class="p">[</span><span class="n">foo_parser</span><span class="p">,</span> <span class="n">bar_parser</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_bar_baz_parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;--baz&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">foo_bar_baz_parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;--foo 1 XXX --baz 2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=&#39;XXX&#39;, baz=&#39;2&#39;, foo=&#39;1&#39;)</span>
</pre></div>
</div>
<p>If you end up with a lot of parsers (as may happen if you make extensive use of subparsers), the <tt class="docutils literal"><span class="pre">parents</span></tt> argument can help dramatically reduce the code duplication.</p>
</div>
<div class="section" id="suppress-anything">
<h3>Suppress anything<a class="headerlink" href="#suppress-anything" title="Permalink to this headline">¶</a></h3>
<p>Both default values and help strings can be suppressed in argparse. Simply provide <tt class="docutils literal"><span class="pre">argparse.SUPPRESS</span></tt> to the appropriate keyword argument:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">prog</span><span class="o">=</span><span class="s">&#39;PROG&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;--secret&#39;</span><span class="p">,</span> <span class="n">help</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">SUPPRESS</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s">&#39;-d&#39;</span><span class="p">,</span> <span class="n">default</span><span class="o">=</span><span class="n">argparse</span><span class="o">.</span><span class="n">SUPPRESS</span><span class="p">)</span>
</pre></div>
</div>
<p>Note that when help for an argument is suppressed, that option will not be displayed in usage or help messages:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">print_help</span><span class="p">()</span>
<span class="go">usage: PROG [-h] [-d D]</span>

<span class="go">optional arguments:</span>
<span class="go">  -h, --help  show this help message and exit</span>
<span class="go">  -d D</span>
</pre></div>
</div>
<p>And when a default is suppressed, the object returned by <a title="parse_args" class="reference external" href="parse_args.html#parse_args"><tt class="xref docutils literal"><span class="pre">parse_args()</span></tt></a> will only include an attribute for the argument if the argument was actually present in the arg strings:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;--secret value&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(secret=&#39;value&#39;)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">(</span><span class="s">&#39;-d value&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(d=&#39;value&#39;, secret=None)</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="upgrading-optparse-code">
<h2>Upgrading optparse code<a class="headerlink" href="#upgrading-optparse-code" title="Permalink to this headline">¶</a></h2>
<p>Originally, the argparse module had attempted to maintain compatibility with optparse. However, optparse was difficult to extend transparently, particularly with the changes required to support the new <tt class="docutils literal"><span class="pre">nargs=</span></tt> specifiers and better usage messges. When most everything in optparse had either been copy-pasted over or monkey-patched, it no longer seemed worthwhile to try to maintain the backwards compatibility.</p>
<p>A partial upgrade path from optparse to argparse:</p>
<ul class="simple">
<li>Replace all <tt class="docutils literal"><span class="pre">add_option()</span></tt> calls with <a title="add_argument" class="reference external" href="add_argument.html#add_argument"><tt class="xref docutils literal"><span class="pre">add_argument()</span></tt></a> calls.</li>
<li>Replace <tt class="docutils literal"><span class="pre">options,</span> <span class="pre">args</span> <span class="pre">=</span> <span class="pre">parser.parse_args()</span></tt> with <tt class="docutils literal"><span class="pre">args</span> <span class="pre">=</span> <span class="pre">parser.parse_args()</span></tt> and add additional <a title="add_argument" class="reference external" href="add_argument.html#add_argument"><tt class="xref docutils literal"><span class="pre">add_argument()</span></tt></a> calls for the positional arguments.</li>
<li>Replace callback actions and the <tt class="docutils literal"><span class="pre">callback_*</span></tt> keyword arguments with <tt class="docutils literal"><span class="pre">type</span></tt> or <tt class="docutils literal"><span class="pre">action</span></tt> arguments.</li>
<li>Replace string names for <tt class="docutils literal"><span class="pre">type</span></tt> keyword arguments with the corresponding type objects (e.g. int, float, complex, etc).</li>
<li>Replace <tt class="docutils literal"><span class="pre">Values</span></tt> with <tt class="docutils literal"><span class="pre">Namespace</span></tt> and <tt class="docutils literal"><span class="pre">OptionError/OptionValueError</span></tt> with <tt class="docutils literal"><span class="pre">ArgumentError</span></tt>.</li>
<li>Replace strings with implicit arguments such as <tt class="docutils literal"><span class="pre">%default</span></tt> or <tt class="docutils literal"><span class="pre">%prog</span></tt> with the standard python syntax to use dictionaries to format strings, that is to say, <tt class="docutils literal"><span class="pre">%(default)s</span></tt> and <tt class="docutils literal"><span class="pre">%(prog)s</span></tt>.</li>
</ul>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="index.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="">argparse vs. optparse</a><ul>
<li><a class="reference external" href="#advantages-of-argparse">Advantages of argparse</a><ul>
<li><a class="reference external" href="#positional-arguments">Positional arguments</a></li>
<li><a class="reference external" href="#optional-arguments">Optional arguments</a></li>
<li><a class="reference external" href="#generated-usage">Generated usage</a></li>
<li><a class="reference external" href="#more-nargs-options">More nargs options</a></li>
<li><a class="reference external" href="#sub-commands">Sub-commands</a></li>
<li><a class="reference external" href="#callable-types">Callable types</a></li>
<li><a class="reference external" href="#extensible-actions">Extensible actions</a></li>
<li><a class="reference external" href="#more-choices">More choices</a></li>
<li><a class="reference external" href="#sharing-arguments">Sharing arguments</a></li>
<li><a class="reference external" href="#suppress-anything">Suppress anything</a></li>
</ul>
</li>
<li><a class="reference external" href="#upgrading-optparse-code">Upgrading optparse code</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="overview.html"
                                  title="previous chapter">Introduction to argparse</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="api-docs.html"
                                  title="next chapter">API documentation</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/argparse-vs-optparse.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="api-docs.html" title="API documentation"
             >next</a> |</li>
        <li class="right" >
          <a href="overview.html" title="Introduction to argparse"
             >previous</a> |</li>
        <li><a href="index.html">argparse v1.0 documentation</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; Copyright 2006-2009, Steven Bethard.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.1.
    </div>
  </body>
</html>