Sophie

Sophie

distrib > Mandriva > current > i586 > media > main-updates > by-pkgid > 8f1462e52e1797a02c97073eed0b7f92 > files > 987

python-docs-2.6.5-2.5mdv2010.2.i586.rpm

<!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>2. Using the Python Interpreter &mdash; Python v2.6.5 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:     '2.6.5',
        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="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.6.5 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.6.5 documentation" href="../index.html" />
    <link rel="up" title="The Python Tutorial" href="index.html" />
    <link rel="next" title="3. An Informal Introduction to Python" href="introduction.html" />
    <link rel="prev" title="1. Whetting Your Appetite" href="appetite.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </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="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="appetite.html" title="1. Whetting Your Appetite"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.5 documentation</a> &raquo;</li>

          <li><a href="index.html" accesskey="U">The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="using-the-python-interpreter">
<span id="tut-using"></span><h1>2. Using the Python Interpreter<a class="headerlink" href="#using-the-python-interpreter" title="Permalink to this headline">¶</a></h1>
<div class="section" id="invoking-the-interpreter">
<span id="tut-invoking"></span><h2>2.1. Invoking the Interpreter<a class="headerlink" href="#invoking-the-interpreter" title="Permalink to this headline">¶</a></h2>
<p>The Python interpreter is usually installed as <tt class="docutils literal"><span class="pre">/usr/bin/python</span></tt> on
those machines where it is available; putting <tt class="docutils literal"><span class="pre">/usr/local/bin</span></tt> in your
Unix shell&#8217;s search path makes it possible to start it by typing the command</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">python</span>
</pre></div>
</div>
<p>to the shell.  Since the choice of the directory where the interpreter lives is
an installation option, other places are possible; check with your local Python
guru or system administrator.  (E.g., <tt class="docutils literal"><span class="pre">/usr/local/python</span></tt> is a popular
alternative location.)</p>
<p>On Windows machines, the Python installation is usually placed in
<tt class="docutils literal"><span class="pre">C:\Python26</span></tt>, though you can change this when you&#8217;re running the
installer.  To add this directory to your path,  you can type the following
command into the command prompt in a DOS box:</p>
<div class="highlight-python"><pre>set path=%path%;C:\python26</pre>
</div>
<p>Typing an end-of-file character (<tt class="docutils literal"><span class="pre">Control-D</span></tt> on Unix, <tt class="docutils literal"><span class="pre">Control-Z</span></tt> on
Windows) at the primary prompt causes the interpreter to exit with a zero exit
status.  If that doesn&#8217;t work, you can exit the interpreter by typing the
following command: <tt class="docutils literal"><span class="pre">quit()</span></tt>.</p>
<p>The interpreter&#8217;s line-editing features usually aren&#8217;t very sophisticated.  On
Unix, whoever installed the interpreter may have enabled support for the GNU
readline library, which adds more elaborate interactive editing and history
features. Perhaps the quickest check to see whether command line editing is
supported is typing Control-P to the first Python prompt you get.  If it beeps,
you have command line editing; see Appendix <a class="reference external" href="interactive.html#tut-interacting"><em>Interactive Input Editing and History Substitution</em></a> for an
introduction to the keys.  If nothing appears to happen, or if <tt class="docutils literal"><span class="pre">^P</span></tt> is echoed,
command line editing isn&#8217;t available; you&#8217;ll only be able to use backspace to
remove characters from the current line.</p>
<p>The interpreter operates somewhat like the Unix shell: when called with standard
input connected to a tty device, it reads and executes commands interactively;
when called with a file name argument or with a file as standard input, it reads
and executes a <em>script</em> from that file.</p>
<p>A second way of starting the interpreter is <tt class="docutils literal"><span class="pre">python</span> <span class="pre">-c</span> <span class="pre">command</span> <span class="pre">[arg]</span> <span class="pre">...</span></tt>,
which executes the statement(s) in <em>command</em>, analogous to the shell&#8217;s
<a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> option.  Since Python statements often contain spaces or other
characters that are special to the shell, it is usually advised to quote
<em>command</em> in its entirety with single quotes.</p>
<p>Some Python modules are also useful as scripts.  These can be invoked using
<tt class="docutils literal"><span class="pre">python</span> <span class="pre">-m</span> <span class="pre">module</span> <span class="pre">[arg]</span> <span class="pre">...</span></tt>, which executes the source file for <em>module</em> as
if you had spelled out its full name on the command line.</p>
<p>Note that there is a difference between <tt class="docutils literal"><span class="pre">python</span> <span class="pre">file</span></tt> and <tt class="docutils literal"><span class="pre">python</span> <span class="pre">&lt;file</span></tt>.
In the latter case, input requests from the program, such as calls to
<a title="input" class="reference external" href="../library/functions.html#input"><tt class="xref docutils literal"><span class="pre">input()</span></tt></a> and <a title="raw_input" class="reference external" href="../library/functions.html#raw_input"><tt class="xref docutils literal"><span class="pre">raw_input()</span></tt></a>, are satisfied from <em>file</em>.  Since this file
has already been read until the end by the parser before the program starts
executing, the program will encounter end-of-file immediately.  In the former
case (which is usually what you want) they are satisfied from whatever file or
device is connected to standard input of the Python interpreter.</p>
<p>When a script file is used, it is sometimes useful to be able to run the script
and enter interactive mode afterwards.  This can be done by passing <a class="reference external" href="../using/cmdline.html#cmdoption-i"><em class="xref">-i</em></a>
before the script.  (This does not work if the script is read from standard
input, for the same reason as explained in the previous paragraph.)</p>
<div class="section" id="argument-passing">
<span id="tut-argpassing"></span><h3>2.1.1. Argument Passing<a class="headerlink" href="#argument-passing" title="Permalink to this headline">¶</a></h3>
<p>When known to the interpreter, the script name and additional arguments
thereafter are passed to the script in the variable <tt class="docutils literal"><span class="pre">sys.argv</span></tt>, which is a
list of strings.  Its length is at least one; when no script and no arguments
are given, <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is an empty string.  When the script name is given as
<tt class="docutils literal"><span class="pre">'-'</span></tt> (meaning  standard input), <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is set to <tt class="docutils literal"><span class="pre">'-'</span></tt>.  When
<a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> <em>command</em> is used, <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt> is set to <tt class="docutils literal"><span class="pre">'-c'</span></tt>.  When
<a class="reference external" href="../using/cmdline.html#cmdoption-m"><em class="xref">-m</em></a> <em>module</em> is used, <tt class="docutils literal"><span class="pre">sys.argv[0]</span></tt>  is set to the full name of the
located module.  Options found after  <a class="reference external" href="../using/cmdline.html#cmdoption-c"><em class="xref">-c</em></a> <em>command</em> or <a class="reference external" href="../using/cmdline.html#cmdoption-m"><em class="xref">-m</em></a>
<em>module</em> are not consumed  by the Python interpreter&#8217;s option processing but
left in <tt class="docutils literal"><span class="pre">sys.argv</span></tt> for  the command or module to handle.</p>
</div>
<div class="section" id="interactive-mode">
<span id="tut-interactive"></span><h3>2.1.2. Interactive Mode<a class="headerlink" href="#interactive-mode" title="Permalink to this headline">¶</a></h3>
<p>When commands are read from a tty, the interpreter is said to be in <em>interactive
mode</em>.  In this mode it prompts for the next command with the <em>primary prompt</em>,
usually three greater-than signs (<tt class="docutils literal"><span class="pre">&gt;&gt;&gt;</span></tt>); for continuation lines it prompts
with the <em>secondary prompt</em>, by default three dots (<tt class="docutils literal"><span class="pre">...</span></tt>). The interpreter
prints a welcome message stating its version number and a copyright notice
before printing the first prompt:</p>
<div class="highlight-python"><pre>python
Python 2.6 (#1, Feb 28 2007, 00:02:06)
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt;</pre>
</div>
<p>Continuation lines are needed when entering a multi-line construct. As an
example, take a look at this <a class="reference external" href="../reference/compound_stmts.html#if"><tt class="xref docutils literal"><span class="pre">if</span></tt></a> statement:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">the_world_is_flat</span> <span class="o">=</span> <span class="mi">1</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">if</span> <span class="n">the_world_is_flat</span><span class="p">:</span>
<span class="gp">... </span>    <span class="k">print</span> <span class="s">&quot;Be careful not to fall off!&quot;</span>
<span class="gp">...</span>
<span class="go">Be careful not to fall off!</span>
</pre></div>
</div>
</div>
</div>
<div class="section" id="the-interpreter-and-its-environment">
<span id="tut-interp"></span><h2>2.2. The Interpreter and Its Environment<a class="headerlink" href="#the-interpreter-and-its-environment" title="Permalink to this headline">¶</a></h2>
<div class="section" id="error-handling">
<span id="tut-error"></span><h3>2.2.1. Error Handling<a class="headerlink" href="#error-handling" title="Permalink to this headline">¶</a></h3>
<p>When an error occurs, the interpreter prints an error message and a stack trace.
In interactive mode, it then returns to the primary prompt; when input came from
a file, it exits with a nonzero exit status after printing the stack trace.
(Exceptions handled by an <a class="reference external" href="../reference/compound_stmts.html#except"><tt class="xref docutils literal"><span class="pre">except</span></tt></a> clause in a <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a> statement
are not errors in this context.)  Some errors are unconditionally fatal and
cause an exit with a nonzero exit; this applies to internal inconsistencies and
some cases of running out of memory.  All error messages are written to the
standard error stream; normal output from executed commands is written to
standard output.</p>
<p>Typing the interrupt character (usually Control-C or DEL) to the primary or
secondary prompt cancels the input and returns to the primary prompt. <a class="footnote-reference" href="#id2" id="id1">[1]</a>
Typing an interrupt while a command is executing raises the
<a title="exceptions.KeyboardInterrupt" class="reference external" href="../library/exceptions.html#exceptions.KeyboardInterrupt"><tt class="xref docutils literal"><span class="pre">KeyboardInterrupt</span></tt></a> exception, which may be handled by a <a class="reference external" href="../reference/compound_stmts.html#try"><tt class="xref docutils literal"><span class="pre">try</span></tt></a>
statement.</p>
</div>
<div class="section" id="executable-python-scripts">
<span id="tut-scripts"></span><h3>2.2.2. Executable Python Scripts<a class="headerlink" href="#executable-python-scripts" title="Permalink to this headline">¶</a></h3>
<p>On BSD&#8217;ish Unix systems, Python scripts can be made directly executable, like
shell scripts, by putting the line</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c">#! /usr/bin/env python</span>
</pre></div>
</div>
<p>(assuming that the interpreter is on the user&#8217;s <span class="target" id="index-1084"></span><strong class="xref">PATH</strong>) at the beginning
of the script and giving the file an executable mode.  The <tt class="docutils literal"><span class="pre">#!</span></tt> must be the
first two characters of the file.  On some platforms, this first line must end
with a Unix-style line ending (<tt class="docutils literal"><span class="pre">'\n'</span></tt>), not a Windows (<tt class="docutils literal"><span class="pre">'\r\n'</span></tt>) line
ending.  Note that the hash, or pound, character, <tt class="docutils literal"><span class="pre">'#'</span></tt>, is used to start a
comment in Python.</p>
<p>The script can be given an executable mode, or permission, using the
<strong>chmod</strong> command:</p>
<div class="highlight-python"><pre>$ chmod +x myscript.py</pre>
</div>
<p>On Windows systems, there is no notion of an &#8220;executable mode&#8221;.  The Python
installer automatically associates <tt class="docutils literal"><span class="pre">.py</span></tt> files with <tt class="docutils literal"><span class="pre">python.exe</span></tt> so that
a double-click on a Python file will run it as a script.  The extension can
also be <tt class="docutils literal"><span class="pre">.pyw</span></tt>, in that case, the console window that normally appears is
suppressed.</p>
</div>
<div class="section" id="source-code-encoding">
<h3>2.2.3. Source Code Encoding<a class="headerlink" href="#source-code-encoding" title="Permalink to this headline">¶</a></h3>
<p>It is possible to use encodings different than ASCII in Python source files. The
best way to do it is to put one more special comment line right after the <tt class="docutils literal"><span class="pre">#!</span></tt>
line to define the source file encoding:</p>
<div class="highlight-python"><pre># -*- coding: encoding -*-</pre>
</div>
<p>With that declaration, all characters in the source file will be treated as
having the encoding <em>encoding</em>, and it will be possible to directly write
Unicode string literals in the selected encoding.  The list of possible
encodings can be found in the Python Library Reference, in the section on
<a title="Encode and decode data and streams." class="reference external" href="../library/codecs.html#module-codecs"><tt class="xref docutils literal"><span class="pre">codecs</span></tt></a>.</p>
<p>For example, to write Unicode literals including the Euro currency symbol, the
ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value
164.  This script will print the value 8364 (the Unicode codepoint corresponding
to the Euro symbol) and then exit:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="c"># -*- coding: iso-8859-15 -*-</span>

<span class="n">currency</span> <span class="o">=</span> <span class="s">u&quot;€&quot;</span>
<span class="k">print</span> <span class="nb">ord</span><span class="p">(</span><span class="n">currency</span><span class="p">)</span>
</pre></div>
</div>
<p>If your editor supports saving files as <tt class="docutils literal"><span class="pre">UTF-8</span></tt> with a UTF-8 <em>byte order mark</em>
(aka BOM), you can use that instead of an encoding declaration. IDLE supports
this capability if <tt class="docutils literal"><span class="pre">Options/General/Default</span> <span class="pre">Source</span> <span class="pre">Encoding/UTF-8</span></tt> is set.
Notice that this signature is not understood in older Python releases (2.2 and
earlier), and also not understood by the operating system for script files with
<tt class="docutils literal"><span class="pre">#!</span></tt> lines (only used on Unix systems).</p>
<p>By using UTF-8 (either through the signature or an encoding declaration),
characters of most languages in the world can be used simultaneously in string
literals and comments.  Using non-ASCII characters in identifiers is not
supported. To display all these characters properly, your editor must recognize
that the file is UTF-8, and it must use a font that supports all the characters
in the file.</p>
</div>
<div class="section" id="the-interactive-startup-file">
<span id="tut-startup"></span><h3>2.2.4. The Interactive Startup File<a class="headerlink" href="#the-interactive-startup-file" title="Permalink to this headline">¶</a></h3>
<p>When you use Python interactively, it is frequently handy to have some standard
commands executed every time the interpreter is started.  You can do this by
setting an environment variable named <span class="target" id="index-1085"></span><a class="reference external" href="../using/cmdline.html#envvar-PYTHONSTARTUP"><strong class="xref">PYTHONSTARTUP</strong></a> to the name of a
file containing your start-up commands.  This is similar to the <tt class="docutils literal"><span class="pre">.profile</span></tt>
feature of the Unix shells.</p>
<p>This file is only read in interactive sessions, not when Python reads commands
from a script, and not when <tt class="docutils literal"><span class="pre">/dev/tty</span></tt> is given as the explicit source of
commands (which otherwise behaves like an interactive session).  It is executed
in the same namespace where interactive commands are executed, so that objects
that it defines or imports can be used without qualification in the interactive
session. You can also change the prompts <tt class="docutils literal"><span class="pre">sys.ps1</span></tt> and <tt class="docutils literal"><span class="pre">sys.ps2</span></tt> in this
file.</p>
<p>If you want to read an additional start-up file from the current directory, you
can program this in the global start-up file using code like <tt class="docutils literal"><span class="pre">if</span>
<span class="pre">os.path.isfile('.pythonrc.py'):</span> <span class="pre">execfile('.pythonrc.py')</span></tt>.  If you want to use
the startup file in a script, you must do this explicitly in the script:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">os</span>
<span class="n">filename</span> <span class="o">=</span> <span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="s">&#39;PYTHONSTARTUP&#39;</span><span class="p">)</span>
<span class="k">if</span> <span class="n">filename</span> <span class="ow">and</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">isfile</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
    <span class="nb">execfile</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
</pre></div>
</div>
<p class="rubric">Footnotes</p>
<table class="docutils footnote" frame="void" id="id2" rules="none">
<colgroup><col class="label" /><col /></colgroup>
<tbody valign="top">
<tr><td class="label"><a class="fn-backref" href="#id1">[1]</a></td><td>A problem with the GNU Readline package may prevent this.</td></tr>
</tbody>
</table>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h3><a href="../contents.html">Table Of Contents</a></h3>
            <ul>
<li><a class="reference external" href="#">2. Using the Python Interpreter</a><ul>
<li><a class="reference external" href="#invoking-the-interpreter">2.1. Invoking the Interpreter</a><ul>
<li><a class="reference external" href="#argument-passing">2.1.1. Argument Passing</a></li>
<li><a class="reference external" href="#interactive-mode">2.1.2. Interactive Mode</a></li>
</ul>
</li>
<li><a class="reference external" href="#the-interpreter-and-its-environment">2.2. The Interpreter and Its Environment</a><ul>
<li><a class="reference external" href="#error-handling">2.2.1. Error Handling</a></li>
<li><a class="reference external" href="#executable-python-scripts">2.2.2. Executable Python Scripts</a></li>
<li><a class="reference external" href="#source-code-encoding">2.2.3. Source Code Encoding</a></li>
<li><a class="reference external" href="#the-interactive-startup-file">2.2.4. The Interactive Startup File</a></li>
</ul>
</li>
</ul>
</li>
</ul>

            <h4>Previous topic</h4>
            <p class="topless"><a href="appetite.html"
                                  title="previous chapter">1. Whetting Your Appetite</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="introduction.html"
                                  title="next chapter">3. An Informal Introduction to Python</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/tutorial/interpreter.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="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="introduction.html" title="3. An Informal Introduction to Python"
             >next</a> |</li>
        <li class="right" >
          <a href="appetite.html" title="1. Whetting Your Appetite"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.5 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Tutorial</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
    &copy; <a href="../copyright.html">Copyright</a> 1990-2010, Python Software Foundation.
    <br />
    The Python Software Foundation is a non-profit corporation.  
    <a href="http://www.python.org/psf/donations/">Please donate.</a>
    <br />
    Last updated on Mar 19, 2010.
    Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.5.
    </div>

  </body>
</html>