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