Debian Codegraph @

Doc/library/code.rst

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