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