blob: 443af699f24ff6927ad7072646b69e937790bde0 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001:mod:`code` --- Interpreter base classes
2========================================
3
4.. module:: code
5 :synopsis: Facilities to implement read-eval-print loops.
6
Andrew Kuchling2e3743c2014-03-19 16:23:01 -04007**Source code:** :source:`Lib/code.py`
Georg Brandl116aa622007-08-15 14:28:22 +00008
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04009--------------
10
Georg Brandl116aa622007-08-15 14:28:22 +000011The ``code`` module provides facilities to implement read-eval-print loops in
12Python. Two classes and convenience functions are included which can be used to
13build applications which provide an interactive interpreter prompt.
14
15
Georg Brandl0d8f0732009-04-05 22:20:44 +000016.. class:: InteractiveInterpreter(locals=None)
Georg Brandl116aa622007-08-15 14:28:22 +000017
18 This class deals with parsing and interpreter state (the user's namespace); it
19 does not deal with input buffering or prompting or input file naming (the
20 filename is always passed in explicitly). The optional *locals* argument
21 specifies the dictionary in which code will be executed; it defaults to a newly
22 created dictionary with key ``'__name__'`` set to ``'__console__'`` and key
23 ``'__doc__'`` set to ``None``.
24
25
Georg Brandl0d8f0732009-04-05 22:20:44 +000026.. class:: InteractiveConsole(locals=None, filename="<console>")
Georg Brandl116aa622007-08-15 14:28:22 +000027
28 Closely emulate the behavior of the interactive Python interpreter. This class
29 builds on :class:`InteractiveInterpreter` and adds prompting using the familiar
30 ``sys.ps1`` and ``sys.ps2``, and input buffering.
31
32
Georg Brandl0d8f0732009-04-05 22:20:44 +000033.. function:: interact(banner=None, readfunc=None, local=None)
Georg Brandl116aa622007-08-15 14:28:22 +000034
Serhiy Storchakabfdcd432013-10-13 23:09:14 +030035 Convenience function to run a read-eval-print loop. This creates a new
36 instance of :class:`InteractiveConsole` and sets *readfunc* to be used as
37 the :meth:`InteractiveConsole.raw_input` method, if provided. If *local* is
38 provided, it is passed to the :class:`InteractiveConsole` constructor for
39 use as the default namespace for the interpreter loop. The :meth:`interact`
40 method of the instance is then run with *banner* passed as the banner to
41 use, if provided. The console object is discarded after use.
Georg Brandl116aa622007-08-15 14:28:22 +000042
43
Georg Brandl0d8f0732009-04-05 22:20:44 +000044.. function:: compile_command(source, filename="<input>", symbol="single")
Georg Brandl116aa622007-08-15 14:28:22 +000045
46 This function is useful for programs that want to emulate Python's interpreter
47 main loop (a.k.a. the read-eval-print loop). The tricky part is to determine
48 when the user has entered an incomplete command that can be completed by
49 entering more text (as opposed to a complete command or a syntax error). This
50 function *almost* always makes the same decision as the real interpreter main
51 loop.
52
53 *source* is the source string; *filename* is the optional filename from which
54 source was read, defaulting to ``'<input>'``; and *symbol* is the optional
55 grammar start symbol, which should be either ``'single'`` (the default) or
56 ``'eval'``.
57
58 Returns a code object (the same as ``compile(source, filename, symbol)``) if the
59 command is complete and valid; ``None`` if the command is incomplete; raises
60 :exc:`SyntaxError` if the command is complete and contains a syntax error, or
61 raises :exc:`OverflowError` or :exc:`ValueError` if the command contains an
62 invalid literal.
63
64
65.. _interpreter-objects:
66
67Interactive Interpreter Objects
68-------------------------------
69
70
Georg Brandl0d8f0732009-04-05 22:20:44 +000071.. method:: InteractiveInterpreter.runsource(source, filename="<input>", symbol="single")
Georg Brandl116aa622007-08-15 14:28:22 +000072
73 Compile and run some source in the interpreter. Arguments are the same as for
74 :func:`compile_command`; the default for *filename* is ``'<input>'``, and for
75 *symbol* is ``'single'``. One several things can happen:
76
77 * The input is incorrect; :func:`compile_command` raised an exception
78 (:exc:`SyntaxError` or :exc:`OverflowError`). A syntax traceback will be
79 printed by calling the :meth:`showsyntaxerror` method. :meth:`runsource`
80 returns ``False``.
81
82 * The input is incomplete, and more input is required; :func:`compile_command`
83 returned ``None``. :meth:`runsource` returns ``True``.
84
85 * The input is complete; :func:`compile_command` returned a code object. The
86 code is executed by calling the :meth:`runcode` (which also handles run-time
87 exceptions, except for :exc:`SystemExit`). :meth:`runsource` returns ``False``.
88
89 The return value can be used to decide whether to use ``sys.ps1`` or ``sys.ps2``
90 to prompt the next line.
91
92
93.. method:: InteractiveInterpreter.runcode(code)
94
95 Execute a code object. When an exception occurs, :meth:`showtraceback` is called
96 to display a traceback. All exceptions are caught except :exc:`SystemExit`,
97 which is allowed to propagate.
98
99 A note about :exc:`KeyboardInterrupt`: this exception may occur elsewhere in
100 this code, and may not always be caught. The caller should be prepared to deal
101 with it.
102
103
Georg Brandl0d8f0732009-04-05 22:20:44 +0000104.. method:: InteractiveInterpreter.showsyntaxerror(filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000105
106 Display the syntax error that just occurred. This does not display a stack
107 trace because there isn't one for syntax errors. If *filename* is given, it is
108 stuffed into the exception instead of the default filename provided by Python's
109 parser, because it always uses ``'<string>'`` when reading from a string. The
110 output is written by the :meth:`write` method.
111
112
113.. method:: InteractiveInterpreter.showtraceback()
114
115 Display the exception that just occurred. We remove the first stack item
116 because it is within the interpreter object implementation. The output is
117 written by the :meth:`write` method.
118
R David Murrayc31e6222014-09-29 11:25:00 -0400119 .. versionchanged:: 3.5 The full chained traceback is displayed instead
120 of just the primary traceback.
121
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123.. method:: InteractiveInterpreter.write(data)
124
125 Write a string to the standard error stream (``sys.stderr``). Derived classes
126 should override this to provide the appropriate output handling as needed.
127
128
129.. _console-objects:
130
131Interactive Console Objects
132---------------------------
133
134The :class:`InteractiveConsole` class is a subclass of
135:class:`InteractiveInterpreter`, and so offers all the methods of the
136interpreter objects as well as the following additions.
137
138
Georg Brandl0d8f0732009-04-05 22:20:44 +0000139.. method:: InteractiveConsole.interact(banner=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000140
Georg Brandlfbc3c3c2013-10-13 21:49:06 +0200141 Closely emulate the interactive Python console. The optional *banner* argument
Georg Brandl116aa622007-08-15 14:28:22 +0000142 specify the banner to print before the first interaction; by default it prints a
143 banner similar to the one printed by the standard Python interpreter, followed
144 by the class name of the console object in parentheses (so as not to confuse
145 this with the real interpreter -- since it's so close!).
146
Georg Brandlfbc3c3c2013-10-13 21:49:06 +0200147 .. versionchanged:: 3.4
148 To suppress printing any banner, pass an empty string.
149
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151.. method:: InteractiveConsole.push(line)
152
153 Push a line of source text to the interpreter. The line should not have a
154 trailing newline; it may have internal newlines. The line is appended to a
155 buffer and the interpreter's :meth:`runsource` method is called with the
156 concatenated contents of the buffer as source. If this indicates that the
157 command was executed or invalid, the buffer is reset; otherwise, the command is
158 incomplete, and the buffer is left as it was after the line was appended. The
159 return value is ``True`` if more input is required, ``False`` if the line was
160 dealt with in some way (this is the same as :meth:`runsource`).
161
162
163.. method:: InteractiveConsole.resetbuffer()
164
165 Remove any unhandled source text from the input buffer.
166
167
Georg Brandl0d8f0732009-04-05 22:20:44 +0000168.. method:: InteractiveConsole.raw_input(prompt="")
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170 Write a prompt and read a line. The returned line does not include the trailing
171 newline. When the user enters the EOF key sequence, :exc:`EOFError` is raised.
172 The base implementation reads from ``sys.stdin``; a subclass may replace this
173 with a different implementation.