• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
11The ``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
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 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
26.. class:: InteractiveConsole(locals=None, filename="<console>")
27
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
33.. function:: interact(banner=None, readfunc=None, local=None, exitmsg=None)
34
35   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* 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.
46
47
48.. function:: compile_command(source, filename="<input>", symbol="single")
49
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 ``'single'`` (the default), ``'eval'``
60   or ``'exec'``.
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
75.. method:: InteractiveInterpreter.runsource(source, filename="<input>", symbol="single")
76
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 of 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
108.. method:: InteractiveInterpreter.showsyntaxerror(filename=None)
109
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
123   .. versionchanged:: 3.5 The full chained traceback is displayed instead
124      of just the primary traceback.
125
126
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
143.. method:: InteractiveConsole.interact(banner=None, exitmsg=None)
144
145   Closely emulate the interactive Python console. The optional *banner* argument
146   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
151   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
153   ``None``, a default message is printed.
154
155   .. versionchanged:: 3.4
156      To suppress printing any banner, pass an empty string.
157
158   .. versionchanged:: 3.6
159      Print an exit message when exiting.
160
161
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
179.. method:: InteractiveConsole.raw_input(prompt="")
180
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.
185