blob: e2c47bab5a0b9173b6b123afc33787ab75c80aac [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
Steven D'Aprano6877ed32016-08-24 01:42:15 +100033.. function:: interact(banner=None, readfunc=None, local=None, exitmsg=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`
Steven D'Aprano6877ed32016-08-24 01:42:15 +100040 method of the instance is then run with *banner* and *exitmsg* passed as the
41 banner and exit message to use, if provided. The console object is discarded
42 after use.
43
44 .. versionchanged:: 3.6
45 Added *exitmsg* parameter.
Georg Brandl116aa622007-08-15 14:28:22 +000046
47
Georg Brandl0d8f0732009-04-05 22:20:44 +000048.. function:: compile_command(source, filename="<input>", symbol="single")
Georg Brandl116aa622007-08-15 14:28:22 +000049
50 This function is useful for programs that want to emulate Python's interpreter
51 main loop (a.k.a. the read-eval-print loop). The tricky part is to determine
52 when the user has entered an incomplete command that can be completed by
53 entering more text (as opposed to a complete command or a syntax error). This
54 function *almost* always makes the same decision as the real interpreter main
55 loop.
56
57 *source* is the source string; *filename* is the optional filename from which
58 source was read, defaulting to ``'<input>'``; and *symbol* is the optional
59 grammar start symbol, which should be either ``'single'`` (the default) or
60 ``'eval'``.
61
62 Returns a code object (the same as ``compile(source, filename, symbol)``) if the
63 command is complete and valid; ``None`` if the command is incomplete; raises
64 :exc:`SyntaxError` if the command is complete and contains a syntax error, or
65 raises :exc:`OverflowError` or :exc:`ValueError` if the command contains an
66 invalid literal.
67
68
69.. _interpreter-objects:
70
71Interactive Interpreter Objects
72-------------------------------
73
74
Georg Brandl0d8f0732009-04-05 22:20:44 +000075.. method:: InteractiveInterpreter.runsource(source, filename="<input>", symbol="single")
Georg Brandl116aa622007-08-15 14:28:22 +000076
77 Compile and run some source in the interpreter. Arguments are the same as for
78 :func:`compile_command`; the default for *filename* is ``'<input>'``, and for
79 *symbol* is ``'single'``. One several things can happen:
80
81 * The input is incorrect; :func:`compile_command` raised an exception
82 (:exc:`SyntaxError` or :exc:`OverflowError`). A syntax traceback will be
83 printed by calling the :meth:`showsyntaxerror` method. :meth:`runsource`
84 returns ``False``.
85
86 * The input is incomplete, and more input is required; :func:`compile_command`
87 returned ``None``. :meth:`runsource` returns ``True``.
88
89 * The input is complete; :func:`compile_command` returned a code object. The
90 code is executed by calling the :meth:`runcode` (which also handles run-time
91 exceptions, except for :exc:`SystemExit`). :meth:`runsource` returns ``False``.
92
93 The return value can be used to decide whether to use ``sys.ps1`` or ``sys.ps2``
94 to prompt the next line.
95
96
97.. method:: InteractiveInterpreter.runcode(code)
98
99 Execute a code object. When an exception occurs, :meth:`showtraceback` is called
100 to display a traceback. All exceptions are caught except :exc:`SystemExit`,
101 which is allowed to propagate.
102
103 A note about :exc:`KeyboardInterrupt`: this exception may occur elsewhere in
104 this code, and may not always be caught. The caller should be prepared to deal
105 with it.
106
107
Georg Brandl0d8f0732009-04-05 22:20:44 +0000108.. method:: InteractiveInterpreter.showsyntaxerror(filename=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000109
110 Display the syntax error that just occurred. This does not display a stack
111 trace because there isn't one for syntax errors. If *filename* is given, it is
112 stuffed into the exception instead of the default filename provided by Python's
113 parser, because it always uses ``'<string>'`` when reading from a string. The
114 output is written by the :meth:`write` method.
115
116
117.. method:: InteractiveInterpreter.showtraceback()
118
119 Display the exception that just occurred. We remove the first stack item
120 because it is within the interpreter object implementation. The output is
121 written by the :meth:`write` method.
122
R David Murrayc31e6222014-09-29 11:25:00 -0400123 .. versionchanged:: 3.5 The full chained traceback is displayed instead
124 of just the primary traceback.
125
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127.. method:: InteractiveInterpreter.write(data)
128
129 Write a string to the standard error stream (``sys.stderr``). Derived classes
130 should override this to provide the appropriate output handling as needed.
131
132
133.. _console-objects:
134
135Interactive Console Objects
136---------------------------
137
138The :class:`InteractiveConsole` class is a subclass of
139:class:`InteractiveInterpreter`, and so offers all the methods of the
140interpreter objects as well as the following additions.
141
142
Steven D'Aprano6877ed32016-08-24 01:42:15 +1000143.. method:: InteractiveConsole.interact(banner=None, exitmsg=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000144
Georg Brandlfbc3c3c2013-10-13 21:49:06 +0200145 Closely emulate the interactive Python console. The optional *banner* argument
Georg Brandl116aa622007-08-15 14:28:22 +0000146 specify the banner to print before the first interaction; by default it prints a
147 banner similar to the one printed by the standard Python interpreter, followed
148 by the class name of the console object in parentheses (so as not to confuse
149 this with the real interpreter -- since it's so close!).
150
Steven D'Aprano6877ed32016-08-24 01:42:15 +1000151 The optional *exitmsg* argument specifies an exit message printed when exiting.
152 Pass the empty string to suppress the exit message. If *exitmsg* is not given or
Serhiy Storchaka989db5c2016-10-19 16:37:13 +0300153 ``None``, a default message is printed.
Steven D'Aprano6877ed32016-08-24 01:42:15 +1000154
Georg Brandlfbc3c3c2013-10-13 21:49:06 +0200155 .. versionchanged:: 3.4
156 To suppress printing any banner, pass an empty string.
157
Steven D'Apranodd51d162016-08-15 04:14:33 +1000158 .. versionchanged:: 3.6
Steven D'Aprano6877ed32016-08-24 01:42:15 +1000159 Print an exit message when exiting.
Steven D'Apranodd51d162016-08-15 04:14:33 +1000160
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162.. method:: InteractiveConsole.push(line)
163
164 Push a line of source text to the interpreter. The line should not have a
165 trailing newline; it may have internal newlines. The line is appended to a
166 buffer and the interpreter's :meth:`runsource` method is called with the
167 concatenated contents of the buffer as source. If this indicates that the
168 command was executed or invalid, the buffer is reset; otherwise, the command is
169 incomplete, and the buffer is left as it was after the line was appended. The
170 return value is ``True`` if more input is required, ``False`` if the line was
171 dealt with in some way (this is the same as :meth:`runsource`).
172
173
174.. method:: InteractiveConsole.resetbuffer()
175
176 Remove any unhandled source text from the input buffer.
177
178
Georg Brandl0d8f0732009-04-05 22:20:44 +0000179.. method:: InteractiveConsole.raw_input(prompt="")
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181 Write a prompt and read a line. The returned line does not include the trailing
182 newline. When the user enters the EOF key sequence, :exc:`EOFError` is raised.
183 The base implementation reads from ``sys.stdin``; a subclass may replace this
184 with a different implementation.