blob: c182511ada3bf870aa333694b2f3771501f57b15 [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
Georg Brandl08a90122012-09-29 09:34:13 +020013The Python interpreter is usually installed as :file:`/usr/local/bin/python3.4`
Georg Brandl3db38ce2008-08-30 09:58:30 +000014on those machines where it is available; putting :file:`/usr/local/bin` in your
Chris Jerdonekdf12f2b2012-09-25 04:20:29 -070015Unix shell's search path makes it possible to start it by typing the command:
16
17.. code-block:: text
Georg Brandl116aa622007-08-15 14:28:22 +000018
Georg Brandl08a90122012-09-29 09:34:13 +020019 python3.4
Georg Brandl116aa622007-08-15 14:28:22 +000020
Georg Brandl3db38ce2008-08-30 09:58:30 +000021to the shell. [#]_ Since the choice of the directory where the interpreter lives
22is an installation option, other places are possible; check with your local
23Python guru or system administrator. (E.g., :file:`/usr/local/python` is a
24popular alternative location.)
Georg Brandl116aa622007-08-15 14:28:22 +000025
26On Windows machines, the Python installation is usually placed in
Georg Brandl08a90122012-09-29 09:34:13 +020027:file:`C:\\Python34`, though you can change this when you're running the
Georg Brandl116aa622007-08-15 14:28:22 +000028installer. To add this directory to your path, you can type the following
29command into the command prompt in a DOS box::
30
Georg Brandl08a90122012-09-29 09:34:13 +020031 set path=%path%;C:\python34
Georg Brandl116aa622007-08-15 14:28:22 +000032
33Typing an end-of-file character (:kbd:`Control-D` on Unix, :kbd:`Control-Z` on
34Windows) at the primary prompt causes the interpreter to exit with a zero exit
35status. If that doesn't work, you can exit the interpreter by typing the
Benjamin Peterson4ac9ce42009-10-04 14:49:41 +000036following command: ``quit()``.
Georg Brandl116aa622007-08-15 14:28:22 +000037
38The interpreter's line-editing features usually aren't very sophisticated. On
39Unix, whoever installed the interpreter may have enabled support for the GNU
40readline library, which adds more elaborate interactive editing and history
41features. Perhaps the quickest check to see whether command line editing is
42supported is typing Control-P to the first Python prompt you get. If it beeps,
43you have command line editing; see Appendix :ref:`tut-interacting` for an
44introduction to the keys. If nothing appears to happen, or if ``^P`` is echoed,
45command line editing isn't available; you'll only be able to use backspace to
46remove characters from the current line.
47
48The interpreter operates somewhat like the Unix shell: when called with standard
49input connected to a tty device, it reads and executes commands interactively;
50when called with a file name argument or with a file as standard input, it reads
51and executes a *script* from that file.
52
53A second way of starting the interpreter is ``python -c command [arg] ...``,
54which executes the statement(s) in *command*, analogous to the shell's
55:option:`-c` option. Since Python statements often contain spaces or other
Georg Brandlf08a9dd2008-06-10 16:57:31 +000056characters that are special to the shell, it is usually advised to quote
57*command* in its entirety with single quotes.
Georg Brandl116aa622007-08-15 14:28:22 +000058
59Some Python modules are also useful as scripts. These can be invoked using
60``python -m module [arg] ...``, which executes the source file for *module* as
61if you had spelled out its full name on the command line.
62
Georg Brandl116aa622007-08-15 14:28:22 +000063When a script file is used, it is sometimes useful to be able to run the script
64and enter interactive mode afterwards. This can be done by passing :option:`-i`
Sandro Tosi69e59a12011-10-31 17:15:39 +010065before the script.
Georg Brandl116aa622007-08-15 14:28:22 +000066
67
68.. _tut-argpassing:
69
70Argument Passing
71----------------
72
73When known to the interpreter, the script name and additional arguments
R. David Murraya3964632010-12-17 16:11:40 +000074thereafter are turned into a list of strings and assigned to the ``argv``
75variable in the ``sys`` module. You can access this list by executing ``import
76sys``. The length of the list is at least one; when no script and no arguments
Georg Brandl116aa622007-08-15 14:28:22 +000077are given, ``sys.argv[0]`` is an empty string. When the script name is given as
78``'-'`` (meaning standard input), ``sys.argv[0]`` is set to ``'-'``. When
79:option:`-c` *command* is used, ``sys.argv[0]`` is set to ``'-c'``. When
80:option:`-m` *module* is used, ``sys.argv[0]`` is set to the full name of the
81located module. Options found after :option:`-c` *command* or :option:`-m`
82*module* are not consumed by the Python interpreter's option processing but
83left in ``sys.argv`` for the command or module to handle.
84
85
86.. _tut-interactive:
87
88Interactive Mode
89----------------
90
91When commands are read from a tty, the interpreter is said to be in *interactive
92mode*. In this mode it prompts for the next command with the *primary prompt*,
93usually three greater-than signs (``>>>``); for continuation lines it prompts
94with the *secondary prompt*, by default three dots (``...``). The interpreter
95prints a welcome message stating its version number and a copyright notice
96before printing the first prompt::
97
Georg Brandl08a90122012-09-29 09:34:13 +020098 $ python3.4
99 Python 3.4 (default, Sep 24 2012, 09:25:04)
Chris Jerdonekdf12f2b2012-09-25 04:20:29 -0700100 [GCC 4.6.3] on linux2
Georg Brandl2d2590d2007-09-28 13:13:35 +0000101 Type "help", "copyright", "credits" or "license" for more information.
Georg Brandl116aa622007-08-15 14:28:22 +0000102 >>>
103
Georg Brandla17487b2009-09-18 07:27:51 +0000104.. XXX update for new releases
Georg Brandl2d2590d2007-09-28 13:13:35 +0000105
Georg Brandl116aa622007-08-15 14:28:22 +0000106Continuation lines are needed when entering a multi-line construct. As an
107example, take a look at this :keyword:`if` statement::
108
109 >>> the_world_is_flat = 1
110 >>> if the_world_is_flat:
Georg Brandl6911e3c2007-09-04 07:15:32 +0000111 ... print("Be careful not to fall off!")
Georg Brandl48310cd2009-01-03 21:18:54 +0000112 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000113 Be careful not to fall off!
114
115
116.. _tut-interp:
117
118The Interpreter and Its Environment
119===================================
120
121
122.. _tut-error:
123
124Error Handling
125--------------
126
127When an error occurs, the interpreter prints an error message and a stack trace.
128In interactive mode, it then returns to the primary prompt; when input came from
129a file, it exits with a nonzero exit status after printing the stack trace.
130(Exceptions handled by an :keyword:`except` clause in a :keyword:`try` statement
131are not errors in this context.) Some errors are unconditionally fatal and
132cause an exit with a nonzero exit; this applies to internal inconsistencies and
133some cases of running out of memory. All error messages are written to the
134standard error stream; normal output from executed commands is written to
135standard output.
136
137Typing the interrupt character (usually Control-C or DEL) to the primary or
138secondary prompt cancels the input and returns to the primary prompt. [#]_
139Typing an interrupt while a command is executing raises the
140:exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:`try`
141statement.
142
143
144.. _tut-scripts:
145
146Executable Python Scripts
147-------------------------
148
149On BSD'ish Unix systems, Python scripts can be made directly executable, like
150shell scripts, by putting the line ::
151
Georg Brandl08a90122012-09-29 09:34:13 +0200152 #! /usr/bin/env python3.4
Georg Brandl116aa622007-08-15 14:28:22 +0000153
154(assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning
155of the script and giving the file an executable mode. The ``#!`` must be the
156first two characters of the file. On some platforms, this first line must end
Georg Brandlc575c902008-09-13 17:46:05 +0000157with a Unix-style line ending (``'\n'``), not a Windows (``'\r\n'``) line
158ending. Note that the hash, or pound, character, ``'#'``, is used to start a
159comment in Python.
Georg Brandl116aa622007-08-15 14:28:22 +0000160
161The script can be given an executable mode, or permission, using the
162:program:`chmod` command::
163
164 $ chmod +x myscript.py
165
Christian Heimese1c98112008-01-21 11:20:28 +0000166On Windows systems, there is no notion of an "executable mode". The Python
167installer automatically associates ``.py`` files with ``python.exe`` so that
168a double-click on a Python file will run it as a script. The extension can
169also be ``.pyw``, in that case, the console window that normally appears is
170suppressed.
171
Georg Brandl116aa622007-08-15 14:28:22 +0000172
Éric Araujo9fbfe152011-06-11 10:34:19 +0200173.. _tut-source-encoding:
174
Georg Brandl116aa622007-08-15 14:28:22 +0000175Source Code Encoding
176--------------------
177
Georg Brandl2d2590d2007-09-28 13:13:35 +0000178By default, Python source files are treated as encoded in UTF-8. In that
179encoding, characters of most languages in the world can be used simultaneously
180in string literals, identifiers and comments --- although the standard library
181only uses ASCII characters for identifiers, a convention that any portable code
182should follow. To display all these characters properly, your editor must
183recognize that the file is UTF-8, and it must use a font that supports all the
184characters in the file.
Georg Brandl6911e3c2007-09-04 07:15:32 +0000185
Georg Brandl2d2590d2007-09-28 13:13:35 +0000186It is also possible to specify a different encoding for source files. In order
187to do this, put one more special comment line right after the ``#!`` line to
188define the source file encoding::
Georg Brandl116aa622007-08-15 14:28:22 +0000189
Georg Brandl48310cd2009-01-03 21:18:54 +0000190 # -*- coding: encoding -*-
Georg Brandl116aa622007-08-15 14:28:22 +0000191
Georg Brandl2d2590d2007-09-28 13:13:35 +0000192With that declaration, everything in the source file will be treated as having
193the encoding *encoding* instead of UTF-8. The list of possible encodings can be
194found in the Python Library Reference, in the section on :mod:`codecs`.
Georg Brandl116aa622007-08-15 14:28:22 +0000195
Georg Brandl2d2590d2007-09-28 13:13:35 +0000196For example, if your editor of choice does not support UTF-8 encoded files and
197insists on using some other encoding, say Windows-1252, you can write::
Georg Brandl116aa622007-08-15 14:28:22 +0000198
Georg Brandl2d2590d2007-09-28 13:13:35 +0000199 # -*- coding: cp-1252 -*-
Georg Brandl116aa622007-08-15 14:28:22 +0000200
Georg Brandl2d2590d2007-09-28 13:13:35 +0000201and still use all characters in the Windows-1252 character set in the source
202files. The special encoding comment must be in the *first or second* line
203within the file.
Georg Brandl116aa622007-08-15 14:28:22 +0000204
205
206.. _tut-startup:
207
208The Interactive Startup File
209----------------------------
210
211When you use Python interactively, it is frequently handy to have some standard
212commands executed every time the interpreter is started. You can do this by
213setting an environment variable named :envvar:`PYTHONSTARTUP` to the name of a
214file containing your start-up commands. This is similar to the :file:`.profile`
215feature of the Unix shells.
216
Christian Heimes5b5e81c2007-12-31 16:14:33 +0000217.. XXX This should probably be dumped in an appendix, since most people
218 don't use Python interactively in non-trivial ways.
Georg Brandl116aa622007-08-15 14:28:22 +0000219
220This file is only read in interactive sessions, not when Python reads commands
221from a script, and not when :file:`/dev/tty` is given as the explicit source of
222commands (which otherwise behaves like an interactive session). It is executed
223in the same namespace where interactive commands are executed, so that objects
224that it defines or imports can be used without qualification in the interactive
225session. You can also change the prompts ``sys.ps1`` and ``sys.ps2`` in this
226file.
227
228If you want to read an additional start-up file from the current directory, you
229can program this in the global start-up file using code like ``if
230os.path.isfile('.pythonrc.py'): exec(open('.pythonrc.py').read())``.
231If you want to use the startup file in a script, you must do this explicitly
232in the script::
233
234 import os
235 filename = os.environ.get('PYTHONSTARTUP')
236 if filename and os.path.isfile(filename):
237 exec(open(filename).read())
238
239
Éric Araujode4f05b2011-08-06 01:51:07 +0200240.. _tut-customize:
241
242The Customization Modules
243-------------------------
244
245Python provides two hooks to let you customize it: :mod:`sitecustomize` and
246:mod:`usercustomize`. To see how it works, you need first to find the location
247of your user site-packages directory. Start Python and run this code:
248
249 >>> import site
250 >>> site.getusersitepackages()
251 '/home/user/.local/lib/python3.2/site-packages'
252
253Now you can create a file named :file:`usercustomize.py` in that directory and
254put anything you want in it. It will affect every invocation of Python, unless
255it is started with the :option:`-s` option to disable the automatic import.
256
257:mod:`sitecustomize` works in the same way, but is typically created by an
258administrator of the computer in the global site-packages directory, and is
259imported before :mod:`usercustomize`. See the documentation of the :mod:`site`
260module for more details.
261
262
Georg Brandl116aa622007-08-15 14:28:22 +0000263.. rubric:: Footnotes
264
Georg Brandla17487b2009-09-18 07:27:51 +0000265.. [#] On Unix, the Python 3.x interpreter is by default not installed with the
Georg Brandl3db38ce2008-08-30 09:58:30 +0000266 executable named ``python``, so that it does not conflict with a
267 simultaneously installed Python 2.x executable.
268
Georg Brandl116aa622007-08-15 14:28:22 +0000269.. [#] A problem with the GNU Readline package may prevent this.