Guido van Rossum | 5d42b5b | 1998-10-22 21:56:44 +0000 | [diff] [blame] | 1 | """Utilities needed to emulate Python's interactive interpreter. |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 2 | |
| 3 | Inspired by similar code by Jeff Epler and Fredrik Lundh. |
| 4 | """ |
Guido van Rossum | 1557a73 | 1997-07-18 16:57:52 +0000 | [diff] [blame] | 5 | |
Guido van Rossum | 5d42b5b | 1998-10-22 21:56:44 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 7 | import sys |
| 8 | import string |
| 9 | import traceback |
Guido van Rossum | 5d42b5b | 1998-10-22 21:56:44 +0000 | [diff] [blame] | 10 | from codeop import compile_command |
Guido van Rossum | 90981e0 | 1997-10-07 14:47:24 +0000 | [diff] [blame] | 11 | |
| 12 | |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 13 | class InteractiveInterpreter: |
| 14 | """Base class for InteractiveConsole. |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 15 | |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 16 | This class deals with parsing and interpreter state (the user's |
| 17 | namespace); it doesn't deal with input buffering or prompting or |
| 18 | input file naming (the filename is always passed in explicitly). |
| 19 | |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 20 | """ |
| 21 | |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 22 | def __init__(self, locals=None): |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 23 | """Constructor. |
| 24 | |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 25 | The optional 'locals' argument specifies the dictionary in |
| 26 | which code will be executed; it defaults to a newly created |
| 27 | dictionary with key "__name__" set to "__console__" and key |
| 28 | "__doc__" set to None. |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 29 | |
| 30 | """ |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 31 | if locals is None: |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 32 | locals = {"__name__": "__console__", "__doc__": None} |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 33 | self.locals = locals |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 34 | |
| 35 | def runsource(self, source, filename="<input>", symbol="single"): |
| 36 | """Compile and run some source in the interpreter. |
| 37 | |
| 38 | Arguments are as for compile_command(). |
| 39 | |
| 40 | One several things can happen: |
| 41 | |
| 42 | 1) The input is incorrect; compile_command() raised an |
| 43 | exception (SyntaxError or OverflowError). A syntax traceback |
| 44 | will be printed by calling the showsyntaxerror() method. |
| 45 | |
| 46 | 2) The input is incomplete, and more input is required; |
| 47 | compile_command() returned None. Nothing happens. |
| 48 | |
| 49 | 3) The input is complete; compile_command() returned a code |
| 50 | object. The code is executed by calling self.runcode() (which |
| 51 | also handles run-time exceptions, except for SystemExit). |
| 52 | |
| 53 | The return value is 1 in case 2, 0 in the other cases (unless |
| 54 | an exception is raised). The return value can be used to |
| 55 | decide whether to use sys.ps1 or sys.ps2 to prompt the next |
| 56 | line. |
| 57 | |
| 58 | """ |
| 59 | try: |
| 60 | code = compile_command(source, filename, symbol) |
| 61 | except (OverflowError, SyntaxError): |
| 62 | # Case 1 |
| 63 | self.showsyntaxerror(filename) |
| 64 | return 0 |
| 65 | |
| 66 | if code is None: |
| 67 | # Case 2 |
| 68 | return 1 |
| 69 | |
| 70 | # Case 3 |
| 71 | self.runcode(code) |
| 72 | return 0 |
| 73 | |
| 74 | def runcode(self, code): |
| 75 | """Execute a code object. |
| 76 | |
| 77 | When an exception occurs, self.showtraceback() is called to |
| 78 | display a traceback. All exceptions are caught except |
| 79 | SystemExit, which is reraised. |
| 80 | |
| 81 | A note about KeyboardInterrupt: this exception may occur |
| 82 | elsewhere in this code, and may not always be caught. The |
| 83 | caller should be prepared to deal with it. |
| 84 | |
| 85 | """ |
| 86 | try: |
| 87 | exec code in self.locals |
| 88 | except SystemExit: |
| 89 | raise |
| 90 | except: |
| 91 | self.showtraceback() |
| 92 | |
| 93 | def showsyntaxerror(self, filename=None): |
| 94 | """Display the syntax error that just occurred. |
| 95 | |
| 96 | This doesn't display a stack trace because there isn't one. |
| 97 | |
| 98 | If a filename is given, it is stuffed in the exception instead |
| 99 | of what was there before (because Python's parser always uses |
| 100 | "<string>" when reading from a string). |
| 101 | |
| 102 | The output is written by self.write(), below. |
| 103 | |
| 104 | """ |
| 105 | type, value, sys.last_traceback = sys.exc_info() |
| 106 | sys.last_type = type |
| 107 | sys.last_value = value |
| 108 | if filename and type is SyntaxError: |
| 109 | # Work hard to stuff the correct filename in the exception |
| 110 | try: |
| 111 | msg, (dummy_filename, lineno, offset, line) = value |
| 112 | except: |
| 113 | # Not the format we expect; leave it alone |
| 114 | pass |
| 115 | else: |
| 116 | # Stuff in the right filename |
| 117 | try: |
| 118 | # Assume SyntaxError is a class exception |
| 119 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
| 120 | except: |
| 121 | # If that failed, assume SyntaxError is a string |
| 122 | value = msg, (filename, lineno, offset, line) |
| 123 | list = traceback.format_exception_only(type, value) |
| 124 | map(self.write, list) |
| 125 | |
| 126 | def showtraceback(self): |
| 127 | """Display the exception that just occurred. |
| 128 | |
| 129 | We remove the first stack item because it is our own code. |
| 130 | |
| 131 | The output is written by self.write(), below. |
| 132 | |
| 133 | """ |
| 134 | try: |
| 135 | type, value, tb = sys.exc_info() |
| 136 | sys.last_type = type |
| 137 | sys.last_value = value |
| 138 | sys.last_traceback = tb |
| 139 | tblist = traceback.extract_tb(tb) |
| 140 | del tblist[:1] |
| 141 | list = traceback.format_list(tblist) |
| 142 | if list: |
| 143 | list.insert(0, "Traceback (innermost last):\n") |
| 144 | list[len(list):] = traceback.format_exception_only(type, value) |
| 145 | finally: |
| 146 | tblist = tb = None |
| 147 | map(self.write, list) |
| 148 | |
| 149 | def write(self, data): |
| 150 | """Write a string. |
| 151 | |
| 152 | The base implementation writes to sys.stderr; a subclass may |
| 153 | replace this with a different implementation. |
| 154 | |
| 155 | """ |
| 156 | sys.stderr.write(data) |
| 157 | |
| 158 | |
| 159 | class InteractiveConsole(InteractiveInterpreter): |
| 160 | """Closely emulate the behavior of the interactive Python interpreter. |
| 161 | |
| 162 | This class builds on InteractiveInterpreter and adds prompting |
| 163 | using the familiar sys.ps1 and sys.ps2, and input buffering. |
| 164 | |
| 165 | """ |
| 166 | |
| 167 | def __init__(self, locals=None, filename="<console>"): |
| 168 | """Constructor. |
| 169 | |
| 170 | The optional locals argument will be passed to the |
| 171 | InteractiveInterpreter base class. |
| 172 | |
| 173 | The optional filename argument should specify the (file)name |
| 174 | of the input stream; it will show up in tracebacks. |
| 175 | |
| 176 | """ |
| 177 | InteractiveInterpreter.__init__(self, locals) |
| 178 | self.filename = filename |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 179 | self.resetbuffer() |
| 180 | |
| 181 | def resetbuffer(self): |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 182 | """Reset the input buffer.""" |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 183 | self.buffer = [] |
| 184 | |
| 185 | def interact(self, banner=None): |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 186 | """Closely emulate the interactive Python console. |
| 187 | |
| 188 | The optional banner argument specify the banner to print |
| 189 | before the first interaction; by default it prints a banner |
| 190 | similar to the one printed by the real Python interpreter, |
| 191 | followed by the current class name in parentheses (so as not |
| 192 | to confuse this with the real interpreter -- since it's so |
| 193 | close!). |
| 194 | |
| 195 | """ |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 196 | try: |
| 197 | sys.ps1 |
| 198 | except AttributeError: |
| 199 | sys.ps1 = ">>> " |
| 200 | try: |
| 201 | sys.ps2 |
| 202 | except AttributeError: |
| 203 | sys.ps2 = "... " |
| 204 | if banner is None: |
| 205 | self.write("Python %s on %s\n%s\n(%s)\n" % |
| 206 | (sys.version, sys.platform, sys.copyright, |
| 207 | self.__class__.__name__)) |
Guido van Rossum | 45e2fbc | 1998-03-26 21:13:24 +0000 | [diff] [blame] | 208 | else: |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 209 | self.write("%s\n" % str(banner)) |
| 210 | more = 0 |
| 211 | while 1: |
| 212 | try: |
| 213 | if more: |
| 214 | prompt = sys.ps2 |
| 215 | else: |
| 216 | prompt = sys.ps1 |
| 217 | try: |
| 218 | line = self.raw_input(prompt) |
| 219 | except EOFError: |
| 220 | self.write("\n") |
| 221 | break |
| 222 | else: |
| 223 | more = self.push(line) |
| 224 | except KeyboardInterrupt: |
| 225 | self.write("\nKeyboardInterrupt\n") |
| 226 | self.resetbuffer() |
| 227 | more = 0 |
| 228 | |
| 229 | def push(self, line): |
| 230 | """Push a line to the interpreter. |
| 231 | |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 232 | The line should not have a trailing newline; it may have |
| 233 | internal newlines. The line is appended to a buffer and the |
| 234 | interpreter's runsource() method is called with the |
| 235 | concatenated contents of the buffer as source. If this |
| 236 | indicates that the command was executed or invalid, the buffer |
| 237 | is reset; otherwise, the command is incomplete, and the buffer |
| 238 | is left as it was after the line was appended. The return |
| 239 | value is 1 if more input is required, 0 if the line was dealt |
| 240 | with in some way (this is the same as runsource()). |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 241 | |
| 242 | """ |
| 243 | self.buffer.append(line) |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 244 | source = string.join(self.buffer, "\n") |
| 245 | more = self.runsource(source, self.filename) |
| 246 | if not more: |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 247 | self.resetbuffer() |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 248 | return more |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 249 | |
| 250 | def raw_input(self, prompt=""): |
| 251 | """Write a prompt and read a line. |
| 252 | |
| 253 | The returned line does not include the trailing newline. |
| 254 | When the user enters the EOF key sequence, EOFError is raised. |
| 255 | |
| 256 | The base implementation uses the built-in function |
| 257 | raw_input(); a subclass may replace this with a different |
| 258 | implementation. |
| 259 | |
| 260 | """ |
| 261 | return raw_input(prompt) |
| 262 | |
| 263 | |
Guido van Rossum | d90ae19 | 1998-10-19 18:42:53 +0000 | [diff] [blame] | 264 | def interact(banner=None, readfunc=None, local=None): |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 265 | """Closely emulate the interactive Python interpreter. |
| 266 | |
| 267 | This is a backwards compatible interface to the InteractiveConsole |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 268 | class. When readfunc is not specified, it attempts to import the |
| 269 | readline module to enable GNU readline if it is available. |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 270 | |
| 271 | Arguments (all optional, all default to None): |
| 272 | |
| 273 | banner -- passed to InteractiveConsole.interact() |
| 274 | readfunc -- if not None, replaces InteractiveConsole.raw_input() |
Guido van Rossum | d90ae19 | 1998-10-19 18:42:53 +0000 | [diff] [blame] | 275 | local -- passed to InteractiveInterpreter.__init__() |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 276 | |
| 277 | """ |
Guido van Rossum | d90ae19 | 1998-10-19 18:42:53 +0000 | [diff] [blame] | 278 | console = InteractiveConsole(local) |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 279 | if readfunc is not None: |
| 280 | console.raw_input = readfunc |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 281 | else: |
| 282 | try: |
| 283 | import readline |
| 284 | except: |
| 285 | pass |
Guido van Rossum | a93b848 | 1998-06-23 19:31:19 +0000 | [diff] [blame] | 286 | console.interact(banner) |
Guido van Rossum | 5227f0f | 1998-09-22 20:38:53 +0000 | [diff] [blame] | 287 | |
| 288 | |
Guido van Rossum | 90981e0 | 1997-10-07 14:47:24 +0000 | [diff] [blame] | 289 | if __name__ == '__main__': |
| 290 | interact() |