You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

184 lines
7.6 KiB

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