summaryrefslogtreecommitdiff
path: root/doc/overview.html
blob: f9e35a55cb6e8dc95a2165d6361191d36d361f08 (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
<!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>Introduction to argparse &mdash; argparse v1.1 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.1',
        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.1 documentation" href="index.html" />
    <link rel="next" title="argparse vs. optparse" href="argparse-vs-optparse.html" />
    <link rel="prev" title="Documentation" href="index.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="argparse-vs-optparse.html" title="argparse vs. optparse"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Documentation"
             accesskey="P">previous</a> |</li>
        <li><a href="index.html">argparse v1.1 documentation</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="introduction-to-argparse">
<h1>Introduction to argparse<a class="headerlink" href="#introduction-to-argparse" title="Permalink to this headline">¶</a></h1>
<p>Pretty much every script that uses the argparse module will start out by creating an <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> object. Typically, this will look something like:</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">description</span><span class="o">=</span><span class="s">&#39;Frabble the foo and the bars&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>The <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> object will hold all the information necessary to parse the command line into a more manageable form for your program.</p>
<div class="section" id="adding-arguments">
<h2>Adding arguments<a class="headerlink" href="#adding-arguments" title="Permalink to this headline">¶</a></h2>
<p>Once you&#8217;ve created an <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a>, you&#8217;ll want to fill it with information about your program arguments. You typically do this by making calls to the <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.  Generally, these calls tell the <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> how to take the strings on the command line and turn them into objects for you. This information is stored and used when <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> is called. For example, if we add some arguments like this:</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">add_argument</span><span class="p">(</span><span class="s">&#39;-f&#39;</span><span class="p">,</span> <span class="s">&#39;--foo&#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="n">help</span><span class="o">=</span><span class="s">&#39;frabble the foos&#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">nargs</span><span class="o">=</span><span class="s">&#39;+&#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">help</span><span class="o">=</span><span class="s">&#39;a bar to be frabbled&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>when we later call <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>, we can expect it to return an object with two attributes, <tt class="docutils literal"><span class="pre">foo</span></tt> and <tt class="docutils literal"><span class="pre">bar</span></tt>.  The <tt class="docutils literal"><span class="pre">foo</span></tt> attribute will be <tt class="xref docutils literal"><span class="pre">True</span></tt> if <tt class="docutils literal"><span class="pre">--foo</span></tt> was supplied at the command-line, and the <tt class="docutils literal"><span class="pre">bar</span></tt> attribute will be a list of ints determined from the remaining command-line arguments:</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;--foo 1 2 3 5 8&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">())</span>
<span class="go">Namespace(bar=[1, 2, 3, 5, 8], foo=True)</span>
</pre></div>
</div>
<p>As you can see from the example above, calls 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> start with either a single string name for positional arguments or a series of option strings (beginning with <tt class="docutils literal"><span class="pre">'-'</span></tt>) for optional arguments.  The remaining keyword arguments 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> specify exactly what sort of action should be carried out when the <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> object encounters the corresponding command-line args.  So in our example above, we are telling the <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> object that when it encounters <tt class="docutils literal"><span class="pre">--foo</span></tt> in the command-line args, it should invoke the <tt class="docutils literal"><span class="pre">'store_true'</span></tt> action.</p>
</div>
<div class="section" id="parsing-arguments">
<h2>Parsing arguments<a class="headerlink" href="#parsing-arguments" title="Permalink to this headline">¶</a></h2>
<p>Once an <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> has been initialized with appropriate calls 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>, it can be instructed to parse the command-line args by calling 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.  This will inspect the command-line, convert each arg to the appropriate type and then invoke the appropriate action.  In most cases, this means a simple namespace object will be built up from attributes parsed out of the command-line.</p>
<p>In the most common case, <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 be called with no arguments, and the <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> will determine the command-line args from <tt class="docutils literal"><span class="pre">sys.argv</span></tt>.  The following example sets up a simple <a title="ArgumentParser" class="reference external" href="ArgumentParser.html#ArgumentParser"><tt class="xref docutils literal"><span class="pre">ArgumentParser</span></tt></a> and then calls <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> in this manner:</p>
<div class="highlight-python"><pre>import argparse

if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
    'integers', metavar='int', type=int, choices=xrange(10),
     nargs='+', help='an integer in the range 0..9')
parser.add_argument(
    '--sum', dest='accumulate', action='store_const', const=sum,
  default=max, help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)</pre>
</div>
<p>Assuming this program is saved in the file <tt class="docutils literal"><span class="pre">script.py</span></tt>, the call to <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> means that we get the following behavior when running the program from the command-line:</p>
<div class="highlight-python"><pre>$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10</pre>
</div>
<p>That&#8217;s pretty much it. You&#8217;re now ready to go write some command line interfaces!</p>
</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="">Introduction to argparse</a><ul>
<li><a class="reference external" href="#adding-arguments">Adding arguments</a></li>
<li><a class="reference external" href="#parsing-arguments">Parsing arguments</a></li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="index.html"
                                  title="previous chapter">Documentation</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="argparse-vs-optparse.html"
                                  title="next chapter">argparse vs. optparse</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="_sources/overview.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="argparse-vs-optparse.html" title="argparse vs. optparse"
             >next</a> |</li>
        <li class="right" >
          <a href="index.html" title="Documentation"
             >previous</a> |</li>
        <li><a href="index.html">argparse v1.1 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>