/Doc/tutorial/interpreter.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 253 lines · 186 code · 67 blank · 0 comment · 0 complexity · b43a22988f8cb7a37604728b88313ca1 MD5 · raw file

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