blob: 20fae9ac2623e64edcdadc74f8a28d1ecb5633aa [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-using:
2
3****************************
4Using the Python Interpreter
5****************************
6
7
8.. _tut-invoking:
9
10Invoking the Interpreter
11========================
12
Benjamin Peterson46ea4f72009-06-27 21:40:27 +000013The Python interpreter is usually installed as :file:`/usr/local/bin/python3.2`
Georg Brandl3db38ce2008-08-30 09:58:30 +000014on those machines where it is available; putting :file:`/usr/local/bin` in your
Georg Brandl116aa622007-08-15 14:28:22 +000015Unix shell's search path makes it possible to start it by typing the command ::
16
Benjamin Peterson46ea4f72009-06-27 21:40:27 +000017 python3.2
Georg Brandl116aa622007-08-15 14:28:22 +000018
Georg Brandl3db38ce2008-08-30 09:58:30 +000019to the shell. [#]_ Since the choice of the directory where the interpreter lives
20is an installation option, other places are possible; check with your local
21Python guru or system administrator. (E.g., :file:`/usr/local/python` is a
22popular alternative location.)
Georg Brandl116aa622007-08-15 14:28:22 +000023
24On Windows machines, the Python installation is usually placed in
Benjamin Peterson46ea4f72009-06-27 21:40:27 +000025:file:`C:\\Python32`, though you can change this when you're running the
Georg Brandl116aa622007-08-15 14:28:22 +000026installer. To add this directory to your path, you can type the following
27command into the command prompt in a DOS box::
28
Benjamin Peterson46ea4f72009-06-27 21:40:27 +000029 set path=%path%;C:\python32
Georg Brandl116aa622007-08-15 14:28:22 +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
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000034following command: ``quit()``.
Georg Brandl116aa622007-08-15 14:28:22 +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 Brandlf08a9dd2008-06-10 16:57:31 +000054characters that are special to the shell, it is usually advised to quote
55*command* in its entirety with single quotes.
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl3db38ce2008-08-30 09:58:30 +000061Note that there is a difference between ``python file`` and ``python
62<file``. In the latter case, input requests from the program, such as calling
Georg Brandl116aa622007-08-15 14:28:22 +000063``sys.stdin.read()``, are satisfied from *file*. Since this file has already
64been read until the end by the parser before the program starts executing, the
65program will encounter end-of-file immediately. In the former case (which is
66usually what you want) they are satisfied from whatever file or device is
67connected 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 Murraya3964632010-12-17 16:11:40 +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 Brandl116aa622007-08-15 14:28:22 +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
Georg Brandla17487b2009-09-18 07:27:51 +0000105 $ python3.2
106 Python 3.2 (py3k, Sep 12 2007, 12:21:02)
Georg Brandl2d2590d2007-09-28 13:13:35 +0000107 [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)] on linux2
108 Type "help", "copyright", "credits" or "license" for more information.
Georg Brandl116aa622007-08-15 14:28:22 +0000109 >>>
110
Georg Brandla17487b2009-09-18 07:27:51 +0000111.. XXX update for new releases
Georg Brandl2d2590d2007-09-28 13:13:35 +0000112
Georg Brandl116aa622007-08-15 14:28:22 +0000113Continuation lines are needed when entering a multi-line construct. As an
114example, take a look at this :keyword:`if` statement::
115
116 >>> the_world_is_flat = 1
117 >>> if the_world_is_flat:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000118 ... print("Be careful not to fall off!")
Georg Brandl48310cd2009-01-03 21:18:54 +0000119 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000120 Be careful not to fall off!
121
122
123.. _tut-interp:
124
125The Interpreter and Its Environment
126===================================
127
128
129.. _tut-error:
130
131Error Handling
132--------------
133
134When an error occurs, the interpreter prints an error message and a stack trace.
135In interactive mode, it then returns to the primary prompt; when input came from
136a file, it exits with a nonzero exit status after printing the stack trace.
137(Exceptions handled by an :keyword:`except` clause in a :keyword:`try` statement
138are not errors in this context.) Some errors are unconditionally fatal and
139cause an exit with a nonzero exit; this applies to internal inconsistencies and
140some cases of running out of memory. All error messages are written to the
141standard error stream; normal output from executed commands is written to
142standard output.
143
144Typing the interrupt character (usually Control-C or DEL) to the primary or
145secondary prompt cancels the input and returns to the primary prompt. [#]_
146Typing an interrupt while a command is executing raises the
147:exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:`try`
148statement.
149
150
151.. _tut-scripts:
152
153Executable Python Scripts
154-------------------------
155
156On BSD'ish Unix systems, Python scripts can be made directly executable, like
157shell scripts, by putting the line ::
158
Ezio Melotti7e5b8892010-04-20 09:41:59 +0000159 #! /usr/bin/env python3.2
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161(assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning
162of the script and giving the file an executable mode. The ``#!`` must be the
163first two characters of the file. On some platforms, this first line must end
Georg Brandlc575c902008-09-13 17:46:05 +0000164with a Unix-style line ending (``'\n'``), not a Windows (``'\r\n'``) line
165ending. Note that the hash, or pound, character, ``'#'``, is used to start a
166comment in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000167
168The script can be given an executable mode, or permission, using the
169:program:`chmod` command::
170
171 $ chmod +x myscript.py
172
Christian Heimese1c98112008-01-21 11:20:28 +0000173On Windows systems, there is no notion of an "executable mode". The Python
174installer automatically associates ``.py`` files with ``python.exe`` so that
175a double-click on a Python file will run it as a script. The extension can
176also be ``.pyw``, in that case, the console window that normally appears is
177suppressed.
178
Georg Brandl116aa622007-08-15 14:28:22 +0000179
180Source Code Encoding
181--------------------
182
Georg Brandl2d2590d2007-09-28 13:13:35 +0000183By default, Python source files are treated as encoded in UTF-8. In that
184encoding, characters of most languages in the world can be used simultaneously
185in string literals, identifiers and comments --- although the standard library
186only uses ASCII characters for identifiers, a convention that any portable code
187should follow. To display all these characters properly, your editor must
188recognize that the file is UTF-8, and it must use a font that supports all the
189characters in the file.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000190
Georg Brandl2d2590d2007-09-28 13:13:35 +0000191It is also possible to specify a different encoding for source files. In order
192to do this, put one more special comment line right after the ``#!`` line to
193define the source file encoding::
Georg Brandl116aa622007-08-15 14:28:22 +0000194
Georg Brandl48310cd2009-01-03 21:18:54 +0000195 # -*- coding: encoding -*-
Georg Brandl116aa622007-08-15 14:28:22 +0000196
Georg Brandl2d2590d2007-09-28 13:13:35 +0000197With that declaration, everything in the source file will be treated as having
198the encoding *encoding* instead of UTF-8. The list of possible encodings can be
199found in the Python Library Reference, in the section on :mod:`codecs`.
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Georg Brandl2d2590d2007-09-28 13:13:35 +0000201For example, if your editor of choice does not support UTF-8 encoded files and
202insists on using some other encoding, say Windows-1252, you can write::
Georg Brandl116aa622007-08-15 14:28:22 +0000203
Georg Brandl2d2590d2007-09-28 13:13:35 +0000204 # -*- coding: cp-1252 -*-
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Georg Brandl2d2590d2007-09-28 13:13:35 +0000206and still use all characters in the Windows-1252 character set in the source
207files. The special encoding comment must be in the *first or second* line
208within the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000209
210
211.. _tut-startup:
212
213The Interactive Startup File
214----------------------------
215
216When you use Python interactively, it is frequently handy to have some standard
217commands executed every time the interpreter is started. You can do this by
218setting an environment variable named :envvar:`PYTHONSTARTUP` to the name of a
219file containing your start-up commands. This is similar to the :file:`.profile`
220feature of the Unix shells.
221
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000222.. XXX This should probably be dumped in an appendix, since most people
223 don't use Python interactively in non-trivial ways.
Georg Brandl116aa622007-08-15 14:28:22 +0000224
225This file is only read in interactive sessions, not when Python reads commands
226from a script, and not when :file:`/dev/tty` is given as the explicit source of
227commands (which otherwise behaves like an interactive session). It is executed
228in the same namespace where interactive commands are executed, so that objects
229that it defines or imports can be used without qualification in the interactive
230session. You can also change the prompts ``sys.ps1`` and ``sys.ps2`` in this
231file.
232
233If you want to read an additional start-up file from the current directory, you
234can program this in the global start-up file using code like ``if
235os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``.
236If you want to use the startup file in a script, you must do this explicitly
237in the script::
238
239 import os
240 filename = os.environ.get('PYTHONSTARTUP')
241 if filename and os.path.isfile(filename):
242 exec(open(filename).read())
243
244
245.. rubric:: Footnotes
246
Georg Brandla17487b2009-09-18 07:27:51 +0000247.. [#] On Unix, the Python 3.x interpreter is by default not installed with the
Georg Brandl3db38ce2008-08-30 09:58:30 +0000248 executable named ``python``, so that it does not conflict with a
249 simultaneously installed Python 2.x executable.
250
Georg Brandl116aa622007-08-15 14:28:22 +0000251.. [#] A problem with the GNU Readline package may prevent this.
252