/Doc/library/code.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 167 lines · 108 code · 59 blank · 0 comment · 0 complexity · 58ec5ff6d9df6a0d223b014142a8fd32 MD5 · raw file

  1. :mod:`code` --- Interpreter base classes
  2. ========================================
  3. .. module:: code
  4. :synopsis: Facilities to implement read-eval-print loops.
  5. The ``code`` module provides facilities to implement read-eval-print loops in
  6. Python. Two classes and convenience functions are included which can be used to
  7. build applications which provide an interactive interpreter prompt.
  8. .. class:: InteractiveInterpreter([locals])
  9. This class deals with parsing and interpreter state (the user's namespace); it
  10. does not deal with input buffering or prompting or input file naming (the
  11. filename is always passed in explicitly). The optional *locals* argument
  12. specifies the dictionary in which code will be executed; it defaults to a newly
  13. created dictionary with key ``'__name__'`` set to ``'__console__'`` and key
  14. ``'__doc__'`` set to ``None``.
  15. .. class:: InteractiveConsole([locals[, filename]])
  16. Closely emulate the behavior of the interactive Python interpreter. This class
  17. builds on :class:`InteractiveInterpreter` and adds prompting using the familiar
  18. ``sys.ps1`` and ``sys.ps2``, and input buffering.
  19. .. function:: interact([banner[, readfunc[, local]]])
  20. Convenience function to run a read-eval-print loop. This creates a new instance
  21. of :class:`InteractiveConsole` and sets *readfunc* to be used as the
  22. :meth:`raw_input` method, if provided. If *local* is provided, it is passed to
  23. the :class:`InteractiveConsole` constructor for use as the default namespace for
  24. the interpreter loop. The :meth:`interact` method of the instance is then run
  25. with *banner* passed as the banner to use, if provided. The console object is
  26. discarded after use.
  27. .. function:: compile_command(source[, filename[, symbol]])
  28. This function is useful for programs that want to emulate Python's interpreter
  29. main loop (a.k.a. the read-eval-print loop). The tricky part is to determine
  30. when the user has entered an incomplete command that can be completed by
  31. entering more text (as opposed to a complete command or a syntax error). This
  32. function *almost* always makes the same decision as the real interpreter main
  33. loop.
  34. *source* is the source string; *filename* is the optional filename from which
  35. source was read, defaulting to ``'<input>'``; and *symbol* is the optional
  36. grammar start symbol, which should be either ``'single'`` (the default) or
  37. ``'eval'``.
  38. Returns a code object (the same as ``compile(source, filename, symbol)``) if the
  39. command is complete and valid; ``None`` if the command is incomplete; raises
  40. :exc:`SyntaxError` if the command is complete and contains a syntax error, or
  41. raises :exc:`OverflowError` or :exc:`ValueError` if the command contains an
  42. invalid literal.
  43. .. _interpreter-objects:
  44. Interactive Interpreter Objects
  45. -------------------------------
  46. .. method:: InteractiveInterpreter.runsource(source[, filename[, symbol]])
  47. Compile and run some source in the interpreter. Arguments are the same as for
  48. :func:`compile_command`; the default for *filename* is ``'<input>'``, and for
  49. *symbol* is ``'single'``. One several things can happen:
  50. * The input is incorrect; :func:`compile_command` raised an exception
  51. (:exc:`SyntaxError` or :exc:`OverflowError`). A syntax traceback will be
  52. printed by calling the :meth:`showsyntaxerror` method. :meth:`runsource`
  53. returns ``False``.
  54. * The input is incomplete, and more input is required; :func:`compile_command`
  55. returned ``None``. :meth:`runsource` returns ``True``.
  56. * The input is complete; :func:`compile_command` returned a code object. The
  57. code is executed by calling the :meth:`runcode` (which also handles run-time
  58. exceptions, except for :exc:`SystemExit`). :meth:`runsource` returns ``False``.
  59. The return value can be used to decide whether to use ``sys.ps1`` or ``sys.ps2``
  60. to prompt the next line.
  61. .. method:: InteractiveInterpreter.runcode(code)
  62. Execute a code object. When an exception occurs, :meth:`showtraceback` is called
  63. to display a traceback. All exceptions are caught except :exc:`SystemExit`,
  64. which is allowed to propagate.
  65. A note about :exc:`KeyboardInterrupt`: this exception may occur elsewhere in
  66. this code, and may not always be caught. The caller should be prepared to deal
  67. with it.
  68. .. method:: InteractiveInterpreter.showsyntaxerror([filename])
  69. Display the syntax error that just occurred. This does not display a stack
  70. trace because there isn't one for syntax errors. If *filename* is given, it is
  71. stuffed into the exception instead of the default filename provided by Python's
  72. parser, because it always uses ``'<string>'`` when reading from a string. The
  73. output is written by the :meth:`write` method.
  74. .. method:: InteractiveInterpreter.showtraceback()
  75. Display the exception that just occurred. We remove the first stack item
  76. because it is within the interpreter object implementation. The output is
  77. written by the :meth:`write` method.
  78. .. method:: InteractiveInterpreter.write(data)
  79. Write a string to the standard error stream (``sys.stderr``). Derived classes
  80. should override this to provide the appropriate output handling as needed.
  81. .. _console-objects:
  82. Interactive Console Objects
  83. ---------------------------
  84. The :class:`InteractiveConsole` class is a subclass of
  85. :class:`InteractiveInterpreter`, and so offers all the methods of the
  86. interpreter objects as well as the following additions.
  87. .. method:: InteractiveConsole.interact([banner])
  88. Closely emulate the interactive Python console. The optional banner argument
  89. specify the banner to print before the first interaction; by default it prints a
  90. banner similar to the one printed by the standard Python interpreter, followed
  91. by the class name of the console object in parentheses (so as not to confuse
  92. this with the real interpreter -- since it's so close!).
  93. .. method:: InteractiveConsole.push(line)
  94. Push a line of source text to the interpreter. The line should not have a
  95. trailing newline; it may have internal newlines. The line is appended to a
  96. buffer and the interpreter's :meth:`runsource` method is called with the
  97. concatenated contents of the buffer as source. If this indicates that the
  98. command was executed or invalid, the buffer is reset; otherwise, the command is
  99. incomplete, and the buffer is left as it was after the line was appended. The
  100. return value is ``True`` if more input is required, ``False`` if the line was
  101. dealt with in some way (this is the same as :meth:`runsource`).
  102. .. method:: InteractiveConsole.resetbuffer()
  103. Remove any unhandled source text from the input buffer.
  104. .. method:: InteractiveConsole.raw_input([prompt])
  105. Write a prompt and read a line. The returned line does not include the trailing
  106. newline. When the user enters the EOF key sequence, :exc:`EOFError` is raised.
  107. The base implementation uses the built-in function :func:`raw_input`; a subclass
  108. may replace this with a different implementation.