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