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