|
1 .. _tut-using: |
|
2 |
|
3 **************************** |
|
4 Using the Python Interpreter |
|
5 **************************** |
|
6 |
|
7 |
|
8 .. _tut-invoking: |
|
9 |
|
10 Invoking the Interpreter |
|
11 ======================== |
|
12 |
|
13 The Python interpreter is usually installed as :file:`/usr/local/bin/python` on |
|
14 those machines where it is available; putting :file:`/usr/local/bin` in your |
|
15 Unix shell's search path makes it possible to start it by typing the command :: |
|
16 |
|
17 python |
|
18 |
|
19 to the shell. Since the choice of the directory where the interpreter lives is |
|
20 an installation option, other places are possible; check with your local Python |
|
21 guru or system administrator. (E.g., :file:`/usr/local/python` is a popular |
|
22 alternative location.) |
|
23 |
|
24 On Windows machines, the Python installation is usually placed in |
|
25 :file:`C:\\Python26`, though you can change this when you're running the |
|
26 installer. To add this directory to your path, you can type the following |
|
27 command into the command prompt in a DOS box:: |
|
28 |
|
29 set path=%path%;C:\python26 |
|
30 |
|
31 Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on |
|
32 Windows) at the primary prompt causes the interpreter to exit with a zero exit |
|
33 status. If that doesn't work, you can exit the interpreter by typing the |
|
34 following commands: ``import sys; sys.exit()``. |
|
35 |
|
36 The interpreter's line-editing features usually aren't very sophisticated. On |
|
37 Unix, whoever installed the interpreter may have enabled support for the GNU |
|
38 readline library, which adds more elaborate interactive editing and history |
|
39 features. Perhaps the quickest check to see whether command line editing is |
|
40 supported is typing Control-P to the first Python prompt you get. If it beeps, |
|
41 you have command line editing; see Appendix :ref:`tut-interacting` for an |
|
42 introduction to the keys. If nothing appears to happen, or if ``^P`` is echoed, |
|
43 command line editing isn't available; you'll only be able to use backspace to |
|
44 remove characters from the current line. |
|
45 |
|
46 The interpreter operates somewhat like the Unix shell: when called with standard |
|
47 input connected to a tty device, it reads and executes commands interactively; |
|
48 when called with a file name argument or with a file as standard input, it reads |
|
49 and executes a *script* from that file. |
|
50 |
|
51 A second way of starting the interpreter is ``python -c command [arg] ...``, |
|
52 which executes the statement(s) in *command*, analogous to the shell's |
|
53 :option:`-c` option. Since Python statements often contain spaces or other |
|
54 characters that are special to the shell, it is usually advised to quote |
|
55 *command* in its entirety with single quotes. |
|
56 |
|
57 Some Python modules are also useful as scripts. These can be invoked using |
|
58 ``python -m module [arg] ...``, which executes the source file for *module* as |
|
59 if you had spelled out its full name on the command line. |
|
60 |
|
61 Note that there is a difference between ``python file`` and ``python <file``. |
|
62 In the latter case, input requests from the program, such as calls to |
|
63 :func:`input` and :func:`raw_input`, are satisfied from *file*. Since this file |
|
64 has already been read until the end by the parser before the program starts |
|
65 executing, the program will encounter end-of-file immediately. In the former |
|
66 case (which is usually what you want) they are satisfied from whatever file or |
|
67 device is connected to standard input of the Python interpreter. |
|
68 |
|
69 When a script file is used, it is sometimes useful to be able to run the script |
|
70 and enter interactive mode afterwards. This can be done by passing :option:`-i` |
|
71 before the script. (This does not work if the script is read from standard |
|
72 input, for the same reason as explained in the previous paragraph.) |
|
73 |
|
74 |
|
75 .. _tut-argpassing: |
|
76 |
|
77 Argument Passing |
|
78 ---------------- |
|
79 |
|
80 When known to the interpreter, the script name and additional arguments |
|
81 thereafter are passed to the script in the variable ``sys.argv``, which is a |
|
82 list of strings. Its length is at least one; when no script and no arguments |
|
83 are given, ``sys.argv[0]`` is an empty string. When the script name is given as |
|
84 ``'-'`` (meaning standard input), ``sys.argv[0]`` is set to ``'-'``. When |
|
85 :option:`-c` *command* is used, ``sys.argv[0]`` is set to ``'-c'``. When |
|
86 :option:`-m` *module* is used, ``sys.argv[0]`` is set to the full name of the |
|
87 located module. Options found after :option:`-c` *command* or :option:`-m` |
|
88 *module* are not consumed by the Python interpreter's option processing but |
|
89 left in ``sys.argv`` for the command or module to handle. |
|
90 |
|
91 |
|
92 .. _tut-interactive: |
|
93 |
|
94 Interactive Mode |
|
95 ---------------- |
|
96 |
|
97 When commands are read from a tty, the interpreter is said to be in *interactive |
|
98 mode*. In this mode it prompts for the next command with the *primary prompt*, |
|
99 usually three greater-than signs (``>>>``); for continuation lines it prompts |
|
100 with the *secondary prompt*, by default three dots (``...``). The interpreter |
|
101 prints a welcome message stating its version number and a copyright notice |
|
102 before printing the first prompt:: |
|
103 |
|
104 python |
|
105 Python 2.6 (#1, Feb 28 2007, 00:02:06) |
|
106 Type "help", "copyright", "credits" or "license" for more information. |
|
107 >>> |
|
108 |
|
109 Continuation lines are needed when entering a multi-line construct. As an |
|
110 example, take a look at this :keyword:`if` statement:: |
|
111 |
|
112 >>> the_world_is_flat = 1 |
|
113 >>> if the_world_is_flat: |
|
114 ... print "Be careful not to fall off!" |
|
115 ... |
|
116 Be careful not to fall off! |
|
117 |
|
118 |
|
119 .. _tut-interp: |
|
120 |
|
121 The Interpreter and Its Environment |
|
122 =================================== |
|
123 |
|
124 |
|
125 .. _tut-error: |
|
126 |
|
127 Error Handling |
|
128 -------------- |
|
129 |
|
130 When an error occurs, the interpreter prints an error message and a stack trace. |
|
131 In interactive mode, it then returns to the primary prompt; when input came from |
|
132 a file, it exits with a nonzero exit status after printing the stack trace. |
|
133 (Exceptions handled by an :keyword:`except` clause in a :keyword:`try` statement |
|
134 are not errors in this context.) Some errors are unconditionally fatal and |
|
135 cause an exit with a nonzero exit; this applies to internal inconsistencies and |
|
136 some cases of running out of memory. All error messages are written to the |
|
137 standard error stream; normal output from executed commands is written to |
|
138 standard output. |
|
139 |
|
140 Typing the interrupt character (usually Control-C or DEL) to the primary or |
|
141 secondary prompt cancels the input and returns to the primary prompt. [#]_ |
|
142 Typing an interrupt while a command is executing raises the |
|
143 :exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:`try` |
|
144 statement. |
|
145 |
|
146 |
|
147 .. _tut-scripts: |
|
148 |
|
149 Executable Python Scripts |
|
150 ------------------------- |
|
151 |
|
152 On BSD'ish Unix systems, Python scripts can be made directly executable, like |
|
153 shell scripts, by putting the line :: |
|
154 |
|
155 #! /usr/bin/env python |
|
156 |
|
157 (assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning |
|
158 of the script and giving the file an executable mode. The ``#!`` must be the |
|
159 first two characters of the file. On some platforms, this first line must end |
|
160 with a Unix-style line ending (``'\n'``), not a Windows (``'\r\n'``) line |
|
161 ending. Note that the hash, or pound, character, ``'#'``, is used to start a |
|
162 comment in Python. |
|
163 |
|
164 The script can be given an executable mode, or permission, using the |
|
165 :program:`chmod` command:: |
|
166 |
|
167 $ chmod +x myscript.py |
|
168 |
|
169 On Windows systems, there is no notion of an "executable mode". The Python |
|
170 installer automatically associates ``.py`` files with ``python.exe`` so that |
|
171 a double-click on a Python file will run it as a script. The extension can |
|
172 also be ``.pyw``, in that case, the console window that normally appears is |
|
173 suppressed. |
|
174 |
|
175 |
|
176 Source Code Encoding |
|
177 -------------------- |
|
178 |
|
179 It is possible to use encodings different than ASCII in Python source files. The |
|
180 best way to do it is to put one more special comment line right after the ``#!`` |
|
181 line to define the source file encoding:: |
|
182 |
|
183 # -*- coding: encoding -*- |
|
184 |
|
185 |
|
186 With that declaration, all characters in the source file will be treated as |
|
187 having the encoding *encoding*, and it will be possible to directly write |
|
188 Unicode string literals in the selected encoding. The list of possible |
|
189 encodings can be found in the Python Library Reference, in the section on |
|
190 :mod:`codecs`. |
|
191 |
|
192 For example, to write Unicode literals including the Euro currency symbol, the |
|
193 ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value |
|
194 164. This script will print the value 8364 (the Unicode codepoint corresponding |
|
195 to the Euro symbol) and then exit:: |
|
196 |
|
197 # -*- coding: iso-8859-15 -*- |
|
198 |
|
199 currency = u"€" |
|
200 print ord(currency) |
|
201 |
|
202 If your editor supports saving files as ``UTF-8`` with a UTF-8 *byte order mark* |
|
203 (aka BOM), you can use that instead of an encoding declaration. IDLE supports |
|
204 this capability if ``Options/General/Default Source Encoding/UTF-8`` is set. |
|
205 Notice that this signature is not understood in older Python releases (2.2 and |
|
206 earlier), and also not understood by the operating system for script files with |
|
207 ``#!`` lines (only used on Unix systems). |
|
208 |
|
209 By using UTF-8 (either through the signature or an encoding declaration), |
|
210 characters of most languages in the world can be used simultaneously in string |
|
211 literals and comments. Using non-ASCII characters in identifiers is not |
|
212 supported. To display all these characters properly, your editor must recognize |
|
213 that the file is UTF-8, and it must use a font that supports all the characters |
|
214 in the file. |
|
215 |
|
216 |
|
217 .. _tut-startup: |
|
218 |
|
219 The Interactive Startup File |
|
220 ---------------------------- |
|
221 |
|
222 When you use Python interactively, it is frequently handy to have some standard |
|
223 commands executed every time the interpreter is started. You can do this by |
|
224 setting an environment variable named :envvar:`PYTHONSTARTUP` to the name of a |
|
225 file containing your start-up commands. This is similar to the :file:`.profile` |
|
226 feature of the Unix shells. |
|
227 |
|
228 .. XXX This should probably be dumped in an appendix, since most people |
|
229 don't use Python interactively in non-trivial ways. |
|
230 |
|
231 This file is only read in interactive sessions, not when Python reads commands |
|
232 from a script, and not when :file:`/dev/tty` is given as the explicit source of |
|
233 commands (which otherwise behaves like an interactive session). It is executed |
|
234 in the same namespace where interactive commands are executed, so that objects |
|
235 that it defines or imports can be used without qualification in the interactive |
|
236 session. You can also change the prompts ``sys.ps1`` and ``sys.ps2`` in this |
|
237 file. |
|
238 |
|
239 If you want to read an additional start-up file from the current directory, you |
|
240 can program this in the global start-up file using code like ``if |
|
241 os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')``. If you want to use |
|
242 the startup file in a script, you must do this explicitly in the script:: |
|
243 |
|
244 import os |
|
245 filename = os.environ.get('PYTHONSTARTUP') |
|
246 if filename and os.path.isfile(filename): |
|
247 execfile(filename) |
|
248 |
|
249 |
|
250 .. rubric:: Footnotes |
|
251 |
|
252 .. [#] A problem with the GNU Readline package may prevent this. |
|
253 |