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