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