Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / html / python / tut / node4.html
CommitLineData
920dae64
AT
1<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2<html>
3<head>
4<link rel="STYLESHEET" href="tut.css" type='text/css' />
5<link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" />
6<link rel='start' href='../index.html' title='Python Documentation Index' />
7<link rel="first" href="tut.html" title='Python Tutorial' />
8<link rel='contents' href='node2.html' title="Contents" />
9<link rel='index' href='node19.html' title='Index' />
10<link rel='last' href='about.html' title='About this document...' />
11<link rel='help' href='about.html' title='About this document...' />
12<link rel="next" href="node5.html" />
13<link rel="prev" href="node3.html" />
14<link rel="parent" href="tut.html" />
15<link rel="next" href="node5.html" />
16<meta name='aesop' content='information' />
17<title>2. Using the Python Interpreter </title>
18</head>
19<body>
20<DIV CLASS="navigation">
21<div id='top-navigation-panel' xml:id='top-navigation-panel'>
22<table align="center" width="100%" cellpadding="0" cellspacing="2">
23<tr>
24<td class='online-navigation'><a rel="prev" title="1. Whetting Your Appetite"
25 href="node3.html"><img src='../icons/previous.png'
26 border='0' height='32' alt='Previous Page' width='32' /></A></td>
27<td class='online-navigation'><a rel="parent" title="Python Tutorial"
28 href="tut.html"><img src='../icons/up.png'
29 border='0' height='32' alt='Up One Level' width='32' /></A></td>
30<td class='online-navigation'><a rel="next" title="3. An Informal Introduction"
31 href="node5.html"><img src='../icons/next.png'
32 border='0' height='32' alt='Next Page' width='32' /></A></td>
33<td align="center" width="100%">Python Tutorial</td>
34<td class='online-navigation'><a rel="contents" title="Table of Contents"
35 href="node2.html"><img src='../icons/contents.png'
36 border='0' height='32' alt='Contents' width='32' /></A></td>
37<td class='online-navigation'><img src='../icons/blank.png'
38 border='0' height='32' alt='' width='32' /></td>
39<td class='online-navigation'><a rel="index" title="Index"
40 href="node19.html"><img src='../icons/index.png'
41 border='0' height='32' alt='Index' width='32' /></A></td>
42</tr></table>
43<div class='online-navigation'>
44<b class="navlabel">Previous:</b>
45<a class="sectref" rel="prev" href="node3.html">1. Whetting Your Appetite</A>
46<b class="navlabel">Up:</b>
47<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
48<b class="navlabel">Next:</b>
49<a class="sectref" rel="next" href="node5.html">3. An Informal Introduction</A>
50</div>
51<hr /></div>
52</DIV>
53<!--End of Navigation Panel-->
54<div class='online-navigation'>
55<!--Table of Child-Links-->
56<A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a>
57
58<UL CLASS="ChildLinks">
59<LI><A href="node4.html#SECTION004100000000000000000">2.1 Invoking the Interpreter</a>
60<UL>
61<LI><A href="node4.html#SECTION004110000000000000000">2.1.1 Argument Passing</a>
62<LI><A href="node4.html#SECTION004120000000000000000">2.1.2 Interactive Mode</a>
63</ul>
64<LI><A href="node4.html#SECTION004200000000000000000">2.2 The Interpreter and Its Environment</a>
65<UL>
66<LI><A href="node4.html#SECTION004210000000000000000">2.2.1 Error Handling</a>
67<LI><A href="node4.html#SECTION004220000000000000000">2.2.2 Executable Python Scripts</a>
68<LI><A href="node4.html#SECTION004230000000000000000">2.2.3 Source Code Encoding</a>
69<LI><A href="node4.html#SECTION004240000000000000000">2.2.4 The Interactive Startup File</a>
70</ul></ul>
71<!--End of Table of Child-Links-->
72</div>
73<HR>
74
75<H1><A NAME="SECTION004000000000000000000"></A><A NAME="using"></A>
76<BR>
772. Using the Python Interpreter
78</H1>
79
80<P>
81
82<H1><A NAME="SECTION004100000000000000000"></A><A NAME="invoking"></A>
83<BR>
842.1 Invoking the Interpreter
85</H1>
86
87<P>
88The Python interpreter is usually installed as
89<span class="file">/usr/local/bin/python</span> on those machines where it is available;
90putting <span class="file">/usr/local/bin</span> in your <span class="Unix">Unix</span> shell's search path
91makes it possible to start it by typing the command
92
93<P>
94<div class="verbatim"><pre>
95python
96</pre></div>
97
98<P>
99to the shell. Since the choice of the directory where the interpreter
100lives is an installation option, other places are possible; check with
101your local Python guru or system administrator. (E.g.,
102<span class="file">/usr/local/python</span> is a popular alternative location.)
103
104<P>
105Typing an end-of-file character (<kbd>Control-D</kbd> on <span class="Unix">Unix</span>,
106<kbd>Control-Z</kbd> on Windows) at the primary prompt causes the
107interpreter to exit with a zero exit status. If that doesn't work,
108you can exit the interpreter by typing the following commands:
109"<tt class="samp">import sys; sys.exit()</tt>".
110
111<P>
112The interpreter's line-editing features usually aren't very
113sophisticated. On <span class="Unix">Unix</span>, whoever installed the interpreter may have
114enabled support for the GNU readline library, which adds more
115elaborate interactive editing and history features. Perhaps the
116quickest check to see whether command line editing is supported is
117typing Control-P to the first Python prompt you get. If it beeps, you
118have command line editing; see Appendix <A HREF="node15.html#interacting">A</A> for an
119introduction to the keys. If nothing appears to happen, or if
120<code>P</code> is echoed, command line editing isn't available; you'll
121only be able to use backspace to remove characters from the current
122line.
123
124<P>
125The interpreter operates somewhat like the <span class="Unix">Unix</span> shell: when called
126with standard input connected to a tty device, it reads and executes
127commands interactively; when called with a file name argument or with
128a file as standard input, it reads and executes a <em>script</em> from
129that file.
130
131<P>
132A second way of starting the interpreter is
133"<tt class="samp"><b class="program">python</b> <b class="programopt">-c</b> <var>command</var> [arg] ...</tt>", which
134executes the statement(s) in <var>command</var>, analogous to the shell's
135<b class="programopt">-c</b> option. Since Python statements often contain spaces
136or other characters that are special to the shell, it is best to quote
137<var>command</var> in its entirety with double quotes.
138
139<P>
140Some Python modules are also useful as scripts. These can be invoked using
141"<tt class="samp"><b class="program">python</b> <b class="programopt">-m</b> <var>module</var> [arg] ...</tt>", which
142executes the source file for <var>module</var> as if you had spelled out its
143full name on the command line.
144
145<P>
146Note that there is a difference between "<tt class="samp">python file</tt>" and
147"<tt class="samp">python &lt;file</tt>". In the latter case, input requests from the
148program, such as calls to <tt class="function">input()</tt> and <tt class="function">raw_input()</tt>, are
149satisfied from <em>file</em>. Since this file has already been read
150until the end by the parser before the program starts executing, the
151program will encounter end-of-file immediately. In the former case
152(which is usually what you want) they are satisfied from whatever file
153or device is connected to standard input of the Python interpreter.
154
155<P>
156When a script file is used, it is sometimes useful to be able to run
157the script and enter interactive mode afterwards. This can be done by
158passing <b class="programopt">-i</b> before the script. (This does not work if the
159script is read from standard input, for the same reason as explained
160in the previous paragraph.)
161
162<P>
163
164<H2><A NAME="SECTION004110000000000000000"></A><A NAME="argPassing"></A>
165<BR>
1662.1.1 Argument Passing
167</H2>
168
169<P>
170When known to the interpreter, the script name and additional
171arguments thereafter are passed to the script in the variable
172<code>sys.argv</code>, which is a list of strings. Its length is at least
173one; when no script and no arguments are given, <code>sys.argv[0]</code> is
174an empty string. When the script name is given as <code>'-'</code> (meaning
175standard input), <code>sys.argv[0]</code> is set to <code>'-'</code>. When
176<b class="programopt">-c</b> <var>command</var> is used, <code>sys.argv[0]</code> is set to
177<code>'-c'</code>. When <b class="programopt">-m</b> <var>module</var> is used, <code>sys.argv[0]</code>
178is set to the full name of the located module. Options found after
179<b class="programopt">-c</b> <var>command</var> or <b class="programopt">-m</b> <var>module</var> are not consumed
180by the Python interpreter's option processing but left in <code>sys.argv</code> for
181the command or module to handle.
182
183<P>
184
185<H2><A NAME="SECTION004120000000000000000"></A><A NAME="interactive"></A>
186<BR>
1872.1.2 Interactive Mode
188</H2>
189
190<P>
191When commands are read from a tty, the interpreter is said to be in
192<em>interactive mode</em>. In this mode it prompts for the next command
193with the <em>primary prompt</em>, usually three greater-than signs
194("<tt class="samp">&gt;<code>&gt;</code>&gt;&nbsp;</tt>"); for continuation lines it prompts with the
195<em>secondary prompt</em>, by default three dots ("<tt class="samp">...&nbsp;</tt>").
196The interpreter prints a welcome message stating its version number
197and a copyright notice before printing the first prompt:
198
199<P>
200<div class="verbatim"><pre>
201python
202Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
203Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
204&gt;&gt;&gt;
205</pre></div>
206
207<P>
208Continuation lines are needed when entering a multi-line construct.
209As an example, take a look at this <tt class="keyword">if</tt> statement:
210
211<P>
212<div class="verbatim"><pre>
213&gt;&gt;&gt; the_world_is_flat = 1
214&gt;&gt;&gt; if the_world_is_flat:
215... print "Be careful not to fall off!"
216...
217Be careful not to fall off!
218</pre></div>
219
220<P>
221
222<H1><A NAME="SECTION004200000000000000000"></A><A NAME="interp"></A>
223<BR>
2242.2 The Interpreter and Its Environment
225</H1>
226
227<P>
228
229<H2><A NAME="SECTION004210000000000000000"></A><A NAME="error"></A>
230<BR>
2312.2.1 Error Handling
232</H2>
233
234<P>
235When an error occurs, the interpreter prints an error
236message and a stack trace. In interactive mode, it then returns to
237the primary prompt; when input came from a file, it exits with a
238nonzero exit status after printing
239the stack trace. (Exceptions handled by an <tt class="keyword">except</tt> clause in a
240<tt class="keyword">try</tt> statement are not errors in this context.) Some errors are
241unconditionally fatal and cause an exit with a nonzero exit; this
242applies to internal inconsistencies and some cases of running out of
243memory. All error messages are written to the standard error stream;
244normal output from executed commands is written to standard
245output.
246
247<P>
248Typing the interrupt character (usually Control-C or DEL) to the
249primary or secondary prompt cancels the input and returns to the
250primary prompt.<A NAME="tex2html1"
251 HREF="#foot123"><SUP>2.1</SUP></A>Typing an interrupt while a command is executing raises the
252<tt class="exception">KeyboardInterrupt</tt> exception, which may be handled by a
253<tt class="keyword">try</tt> statement.
254
255<P>
256
257<H2><A NAME="SECTION004220000000000000000"></A><A NAME="scripts"></A>
258<BR>
2592.2.2 Executable Python Scripts
260</H2>
261
262<P>
263On BSD'ish <span class="Unix">Unix</span> systems, Python scripts can be made directly
264executable, like shell scripts, by putting the line
265
266<P>
267<div class="verbatim"><pre>
268#! /usr/bin/env python
269</pre></div>
270
271<P>
272(assuming that the interpreter is on the user's <a class="envvar" id='l2h-1' xml:id='l2h-1'>PATH</a>) at the
273beginning of the script and giving the file an executable mode. The
274"<tt class="samp">#!</tt>" must be the first two characters of the file. On some
275platforms, this first line must end with a <span class="Unix">Unix</span>-style line ending
276("<tt class="character">&#92;n</tt>"), not a Mac OS ("<tt class="character">&#92;r</tt>") or Windows
277("<tt class="character">&#92;r&#92;n</tt>") line ending. Note that
278the hash, or pound, character, "<tt class="character">#</tt>", is used to start a
279comment in Python.
280
281<P>
282The script can be given a executable mode, or permission, using the
283<b class="program">chmod</b> command:
284
285<P>
286<div class="verbatim"><pre>
287$ chmod +x myscript.py
288</pre></div>
289<P>
290
291<H2><A NAME="SECTION004230000000000000000">
2922.2.3 Source Code Encoding</A>
293</H2>
294
295<P>
296It is possible to use encodings different than ASCII in Python source
297files. The best way to do it is to put one more special comment line
298right after the <code>#!</code> line to define the source file encoding:
299
300<P>
301<div class="verbatim"><pre><TT>
302 # -*- coding: <var>encoding</var> -*-
303 </TT></pre></div>
304
305<P>
306With that declaration, all characters in the source file will be treated as
307having the encoding <var>encoding</var>, and it will be
308possible to directly write Unicode string literals in the selected
309encoding. The list of possible encodings can be found in the
310<em class="citetitle"><a
311 href="../lib/lib.html"
312 title="Python Library Reference"
313 >Python Library Reference</a></em>, in the section
314on <a class="ulink" href="../lib/module-codecs.html"
315 ><tt class="module">codecs</tt></a>.
316
317<P>
318For example, to write Unicode literals including the Euro currency
319symbol, the ISO-8859-15 encoding can be used, with the Euro symbol
320having the ordinal value 164. This script will print the value 8364
321(the Unicode codepoint corresponding to the Euro symbol) and then
322exit:
323
324<P>
325<div class="verbatim"><pre><TT>
326 # -*- coding: iso-8859-15 -*-
327
328 currency = u&#34;&#8364;&#34;
329 print ord(currency)
330 </TT></pre></div>
331
332<P>
333If your editor supports saving files as <code>UTF-8</code> with a UTF-8
334<em>byte order mark</em> (aka BOM), you can use that instead of an
335encoding declaration. IDLE supports this capability if
336<code>Options/General/Default Source Encoding/UTF-8</code> is set. Notice
337that this signature is not understood in older Python releases (2.2
338and earlier), and also not understood by the operating system for
339script files with <code>#!</code> lines (only used on <span class="Unix">Unix</span> systems).
340
341<P>
342By using UTF-8 (either through the signature or an encoding
343declaration), characters of most languages in the world can be used
344simultaneously in string literals and comments. Using non-ASCII
345characters in identifiers is not supported. To display all these
346characters properly, your editor must recognize that the file is
347UTF-8, and it must use a font that supports all the characters in the
348file.
349
350<P>
351
352<H2><A NAME="SECTION004240000000000000000"></A><A NAME="startup"></A>
353<BR>
3542.2.4 The Interactive Startup File
355</H2>
356
357<P>
358When you use Python interactively, it is frequently handy to have some
359standard commands executed every time the interpreter is started. You
360can do this by setting an environment variable named
361<a class="envvar" id='l2h-2' xml:id='l2h-2'>PYTHONSTARTUP</a> to the name of a file containing your start-up
362commands. This is similar to the <span class="file">.profile</span> feature of the
363<span class="Unix">Unix</span> shells.
364
365<P>
366This file is only read in interactive sessions, not when Python reads
367commands from a script, and not when <span class="file">/dev/tty</span> is given as the
368explicit source of commands (which otherwise behaves like an
369interactive session). It is executed in the same namespace where
370interactive commands are executed, so that objects that it defines or
371imports can be used without qualification in the interactive session.
372You can also change the prompts <code>sys.ps1</code> and <code>sys.ps2</code> in
373this file.
374
375<P>
376If you want to read an additional start-up file from the current
377directory, you can program this in the global start-up file using code
378like "<tt class="samp">if os.path.isfile('.pythonrc.py'):
379execfile('.pythonrc.py')</tt>". If you want to use the startup file in a
380script, you must do this explicitly in the script:
381
382<P>
383<div class="verbatim"><pre>
384import os
385filename = os.environ.get('PYTHONSTARTUP')
386if filename and os.path.isfile(filename):
387 execfile(filename)
388</pre></div>
389
390<P>
391<BR><HR><H4>Footnotes</H4>
392<DL>
393<DT><A NAME="foot123">... prompt.</A><A
394 HREF="node4.html#tex2html1"><SUP>2.1</SUP></A></DT>
395<DD>
396 A problem with the GNU Readline package may prevent this.
397
398
399</DD>
400</DL>
401<DIV CLASS="navigation">
402<div class='online-navigation'>
403<p></p><hr />
404<table align="center" width="100%" cellpadding="0" cellspacing="2">
405<tr>
406<td class='online-navigation'><a rel="prev" title="1. Whetting Your Appetite"
407 href="node3.html"><img src='../icons/previous.png'
408 border='0' height='32' alt='Previous Page' width='32' /></A></td>
409<td class='online-navigation'><a rel="parent" title="Python Tutorial"
410 href="tut.html"><img src='../icons/up.png'
411 border='0' height='32' alt='Up One Level' width='32' /></A></td>
412<td class='online-navigation'><a rel="next" title="3. An Informal Introduction"
413 href="node5.html"><img src='../icons/next.png'
414 border='0' height='32' alt='Next Page' width='32' /></A></td>
415<td align="center" width="100%">Python Tutorial</td>
416<td class='online-navigation'><a rel="contents" title="Table of Contents"
417 href="node2.html"><img src='../icons/contents.png'
418 border='0' height='32' alt='Contents' width='32' /></A></td>
419<td class='online-navigation'><img src='../icons/blank.png'
420 border='0' height='32' alt='' width='32' /></td>
421<td class='online-navigation'><a rel="index" title="Index"
422 href="node19.html"><img src='../icons/index.png'
423 border='0' height='32' alt='Index' width='32' /></A></td>
424</tr></table>
425<div class='online-navigation'>
426<b class="navlabel">Previous:</b>
427<a class="sectref" rel="prev" href="node3.html">1. Whetting Your Appetite</A>
428<b class="navlabel">Up:</b>
429<a class="sectref" rel="parent" href="tut.html">Python Tutorial</A>
430<b class="navlabel">Next:</b>
431<a class="sectref" rel="next" href="node5.html">3. An Informal Introduction</A>
432</div>
433</div>
434<hr />
435<span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span>
436</DIV>
437<!--End of Navigation Panel-->
438<ADDRESS>
439See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
440</ADDRESS>
441</BODY>
442</HTML>