Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 |
Georg Brandl | 9352f1c | 2010-04-10 11:16:59 +0000 | [diff] [blame] | 25 | :file:`C:\\Python27`, though you can change this when you're running the |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 9352f1c | 2010-04-10 11:16:59 +0000 | [diff] [blame] | 29 | set path=%path%;C:\python27 |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 |
Georg Brandl | 4d94d31 | 2009-09-18 07:22:41 +0000 | [diff] [blame] | 34 | following command: ``quit()``. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 |
Georg Brandl | c5a235b | 2008-05-30 19:17:29 +0000 | [diff] [blame] | 54 | characters that are special to the shell, it is usually advised to quote |
| 55 | *command* in its entirety with single quotes. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 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 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 61 | When a script file is used, it is sometimes useful to be able to run the script |
| 62 | and enter interactive mode afterwards. This can be done by passing :option:`-i` |
| 63 | before the script. (This does not work if the script is read from standard |
| 64 | input, for the same reason as explained in the previous paragraph.) |
| 65 | |
| 66 | |
| 67 | .. _tut-argpassing: |
| 68 | |
| 69 | Argument Passing |
| 70 | ---------------- |
| 71 | |
| 72 | When known to the interpreter, the script name and additional arguments |
R. David Murray | 561b96f | 2011-02-11 17:25:54 +0000 | [diff] [blame] | 73 | thereafter are turned into a list of strings and assigned to the ``argv`` |
| 74 | variable in the ``sys`` module. You can access this list by executing ``import |
| 75 | sys``. The length of the list is at least one; when no script and no arguments |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 76 | are given, ``sys.argv[0]`` is an empty string. When the script name is given as |
| 77 | ``'-'`` (meaning standard input), ``sys.argv[0]`` is set to ``'-'``. When |
| 78 | :option:`-c` *command* is used, ``sys.argv[0]`` is set to ``'-c'``. When |
| 79 | :option:`-m` *module* is used, ``sys.argv[0]`` is set to the full name of the |
| 80 | located module. Options found after :option:`-c` *command* or :option:`-m` |
| 81 | *module* are not consumed by the Python interpreter's option processing but |
| 82 | left in ``sys.argv`` for the command or module to handle. |
| 83 | |
| 84 | |
| 85 | .. _tut-interactive: |
| 86 | |
| 87 | Interactive Mode |
| 88 | ---------------- |
| 89 | |
| 90 | When commands are read from a tty, the interpreter is said to be in *interactive |
| 91 | mode*. In this mode it prompts for the next command with the *primary prompt*, |
| 92 | usually three greater-than signs (``>>>``); for continuation lines it prompts |
| 93 | with the *secondary prompt*, by default three dots (``...``). The interpreter |
| 94 | prints a welcome message stating its version number and a copyright notice |
| 95 | before printing the first prompt:: |
| 96 | |
| 97 | python |
Georg Brandl | 9352f1c | 2010-04-10 11:16:59 +0000 | [diff] [blame] | 98 | Python 2.7 (#1, Feb 28 2010, 00:02:06) |
Neal Norwitz | 76e4d62 | 2007-11-19 01:46:20 +0000 | [diff] [blame] | 99 | Type "help", "copyright", "credits" or "license" for more information. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 100 | >>> |
| 101 | |
| 102 | Continuation lines are needed when entering a multi-line construct. As an |
| 103 | example, take a look at this :keyword:`if` statement:: |
| 104 | |
| 105 | >>> the_world_is_flat = 1 |
| 106 | >>> if the_world_is_flat: |
| 107 | ... print "Be careful not to fall off!" |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 108 | ... |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 109 | Be careful not to fall off! |
| 110 | |
| 111 | |
| 112 | .. _tut-interp: |
| 113 | |
| 114 | The Interpreter and Its Environment |
| 115 | =================================== |
| 116 | |
| 117 | |
| 118 | .. _tut-error: |
| 119 | |
| 120 | Error Handling |
| 121 | -------------- |
| 122 | |
| 123 | When an error occurs, the interpreter prints an error message and a stack trace. |
| 124 | In interactive mode, it then returns to the primary prompt; when input came from |
| 125 | a file, it exits with a nonzero exit status after printing the stack trace. |
| 126 | (Exceptions handled by an :keyword:`except` clause in a :keyword:`try` statement |
| 127 | are not errors in this context.) Some errors are unconditionally fatal and |
| 128 | cause an exit with a nonzero exit; this applies to internal inconsistencies and |
| 129 | some cases of running out of memory. All error messages are written to the |
| 130 | standard error stream; normal output from executed commands is written to |
| 131 | standard output. |
| 132 | |
| 133 | Typing the interrupt character (usually Control-C or DEL) to the primary or |
| 134 | secondary prompt cancels the input and returns to the primary prompt. [#]_ |
| 135 | Typing an interrupt while a command is executing raises the |
| 136 | :exc:`KeyboardInterrupt` exception, which may be handled by a :keyword:`try` |
| 137 | statement. |
| 138 | |
| 139 | |
| 140 | .. _tut-scripts: |
| 141 | |
| 142 | Executable Python Scripts |
| 143 | ------------------------- |
| 144 | |
| 145 | On BSD'ish Unix systems, Python scripts can be made directly executable, like |
| 146 | shell scripts, by putting the line :: |
| 147 | |
| 148 | #! /usr/bin/env python |
| 149 | |
| 150 | (assuming that the interpreter is on the user's :envvar:`PATH`) at the beginning |
| 151 | of the script and giving the file an executable mode. The ``#!`` must be the |
| 152 | first two characters of the file. On some platforms, this first line must end |
Georg Brandl | 9af9498 | 2008-09-13 17:41:16 +0000 | [diff] [blame] | 153 | with a Unix-style line ending (``'\n'``), not a Windows (``'\r\n'``) line |
| 154 | ending. Note that the hash, or pound, character, ``'#'``, is used to start a |
| 155 | comment in Python. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 156 | |
| 157 | The script can be given an executable mode, or permission, using the |
| 158 | :program:`chmod` command:: |
| 159 | |
| 160 | $ chmod +x myscript.py |
| 161 | |
Georg Brandl | 23bf837 | 2008-01-20 19:40:58 +0000 | [diff] [blame] | 162 | On Windows systems, there is no notion of an "executable mode". The Python |
| 163 | installer automatically associates ``.py`` files with ``python.exe`` so that |
| 164 | a double-click on a Python file will run it as a script. The extension can |
| 165 | also be ``.pyw``, in that case, the console window that normally appears is |
| 166 | suppressed. |
| 167 | |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 168 | |
| 169 | Source Code Encoding |
| 170 | -------------------- |
| 171 | |
| 172 | It is possible to use encodings different than ASCII in Python source files. The |
| 173 | best way to do it is to put one more special comment line right after the ``#!`` |
| 174 | line to define the source file encoding:: |
| 175 | |
Georg Brandl | c62ef8b | 2009-01-03 20:55:06 +0000 | [diff] [blame] | 176 | # -*- coding: encoding -*- |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 177 | |
| 178 | |
| 179 | With that declaration, all characters in the source file will be treated as |
| 180 | having the encoding *encoding*, and it will be possible to directly write |
| 181 | Unicode string literals in the selected encoding. The list of possible |
| 182 | encodings can be found in the Python Library Reference, in the section on |
| 183 | :mod:`codecs`. |
| 184 | |
| 185 | For example, to write Unicode literals including the Euro currency symbol, the |
| 186 | ISO-8859-15 encoding can be used, with the Euro symbol having the ordinal value |
| 187 | 164. This script will print the value 8364 (the Unicode codepoint corresponding |
| 188 | to the Euro symbol) and then exit:: |
| 189 | |
| 190 | # -*- coding: iso-8859-15 -*- |
| 191 | |
| 192 | currency = u"€" |
| 193 | print ord(currency) |
| 194 | |
| 195 | If your editor supports saving files as ``UTF-8`` with a UTF-8 *byte order mark* |
| 196 | (aka BOM), you can use that instead of an encoding declaration. IDLE supports |
| 197 | this capability if ``Options/General/Default Source Encoding/UTF-8`` is set. |
| 198 | Notice that this signature is not understood in older Python releases (2.2 and |
| 199 | earlier), and also not understood by the operating system for script files with |
| 200 | ``#!`` lines (only used on Unix systems). |
| 201 | |
| 202 | By using UTF-8 (either through the signature or an encoding declaration), |
| 203 | characters of most languages in the world can be used simultaneously in string |
| 204 | literals and comments. Using non-ASCII characters in identifiers is not |
| 205 | supported. To display all these characters properly, your editor must recognize |
| 206 | that the file is UTF-8, and it must use a font that supports all the characters |
| 207 | in the file. |
| 208 | |
| 209 | |
| 210 | .. _tut-startup: |
| 211 | |
| 212 | The Interactive Startup File |
| 213 | ---------------------------- |
| 214 | |
| 215 | When you use Python interactively, it is frequently handy to have some standard |
| 216 | commands executed every time the interpreter is started. You can do this by |
| 217 | setting an environment variable named :envvar:`PYTHONSTARTUP` to the name of a |
| 218 | file containing your start-up commands. This is similar to the :file:`.profile` |
| 219 | feature of the Unix shells. |
| 220 | |
Georg Brandl | b19be57 | 2007-12-29 10:57:00 +0000 | [diff] [blame] | 221 | .. XXX This should probably be dumped in an appendix, since most people |
| 222 | don't use Python interactively in non-trivial ways. |
Georg Brandl | 8ec7f65 | 2007-08-15 14:28:01 +0000 | [diff] [blame] | 223 | |
| 224 | This file is only read in interactive sessions, not when Python reads commands |
| 225 | from a script, and not when :file:`/dev/tty` is given as the explicit source of |
| 226 | commands (which otherwise behaves like an interactive session). It is executed |
| 227 | in the same namespace where interactive commands are executed, so that objects |
| 228 | that it defines or imports can be used without qualification in the interactive |
| 229 | session. You can also change the prompts ``sys.ps1`` and ``sys.ps2`` in this |
| 230 | file. |
| 231 | |
| 232 | If you want to read an additional start-up file from the current directory, you |
| 233 | can program this in the global start-up file using code like ``if |
| 234 | os.path.isfile('.pythonrc.py'): execfile('.pythonrc.py')``. If you want to use |
| 235 | the startup file in a script, you must do this explicitly in the script:: |
| 236 | |
| 237 | import os |
| 238 | filename = os.environ.get('PYTHONSTARTUP') |
| 239 | if filename and os.path.isfile(filename): |
| 240 | execfile(filename) |
| 241 | |
| 242 | |
| 243 | .. rubric:: Footnotes |
| 244 | |
| 245 | .. [#] A problem with the GNU Readline package may prevent this. |
| 246 | |