| 1 |
"""Utilities needed to emulate Python's interactive interpreter. |
| 2 |
|
| 3 |
""" |
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
import sys |
| 9 |
import traceback |
| 10 |
from codeop import CommandCompiler, compile_command |
| 11 |
|
| 12 |
__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact", |
| 13 |
"compile_command"] |
| 14 |
|
| 15 |
class InteractiveInterpreter: |
| 16 |
"""Base class for InteractiveConsole. |
| 17 |
|
| 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 |
|
| 22 |
""" |
| 23 |
|
| 24 |
def __init__(self, locals=None): |
| 25 |
"""Constructor. |
| 26 |
|
| 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. |
| 31 |
|
| 32 |
""" |
| 33 |
if locals is None: |
| 34 |
locals = {"__name__": "__console__", "__doc__": None} |
| 35 |
self.locals = locals |
| 36 |
self.compile = CommandCompiler() |
| 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 of 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 |
|
| 56 |
The return value is True in case 2, False in the other cases (unless |
| 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: |
| 63 |
code = self.compile(source, filename, symbol) |
| 64 |
except (OverflowError, SyntaxError, ValueError): |
| 65 |
|
| 66 |
self.showsyntaxerror(filename, source=source) |
| 67 |
return False |
| 68 |
|
| 69 |
if code is None: |
| 70 |
|
| 71 |
return True |
| 72 |
|
| 73 |
|
| 74 |
self.runcode(code) |
| 75 |
return False |
| 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: |
| 90 |
exec(code, self.locals) |
| 91 |
except SystemExit: |
| 92 |
raise |
| 93 |
except: |
| 94 |
self.showtraceback() |
| 95 |
|
| 96 |
def showsyntaxerror(self, filename=None, **kwargs): |
| 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 |
""" |
| 108 |
typ, value, tb = sys.exc_info() |
| 109 |
if filename and issubclass(typ, SyntaxError): |
| 110 |
value.filename = filename |
| 111 |
if sys.excepthook is sys.__excepthook__: |
| 112 |
lines = traceback.format_exception_only(type, value) |
| 113 |
self.write(''.join(lines)) |
| 114 |
else: |
| 115 |
|
| 116 |
|
| 117 |
sys.excepthook(type, value, tb) |
| 118 |
|
| 119 |
def showtraceback(self, **kwargs): |
| 120 |
"""Display the exception that just occurred. |
| 121 |
|
| 122 |
We remove the first stack item because it is our own code. |
| 123 |
|
| 124 |
The output is written by self.write(), below. |
| 125 |
|
| 126 |
""" |
| 127 |
|
| 128 |
try: |
| 129 |
typ, value, tb = sys.exc_info() |
| 130 |
source = kwargs.pop("source", "") |
| 131 |
self._showtraceback(typ, value, tb.tb_next, source) |
| 132 |
finally: |
| 133 |
typ = value = tb = None |
| 134 |
|
| 135 |
def _showtraceback(self, typ, value, tb, source="", colorize=False, limit=None): |
| 136 |
sys.last_type = typ |
| 137 |
sys.last_traceback = tb |
| 138 |
value = value.with_traceback(tb) |
| 139 |
|
| 140 |
lines = source.splitlines() |
| 141 |
if (source and typ is SyntaxError |
| 142 |
and not value.text and len(lines) >= value.lineno): |
| 143 |
value.text = lines[value.lineno - 1] |
| 144 |
sys.last_exc = sys.last_value = value |
| 145 |
if sys.excepthook is sys.__excepthook__: |
| 146 |
self._excepthook(typ, value, tb) |
| 147 |
else: |
| 148 |
|
| 149 |
|
| 150 |
try: |
| 151 |
sys.excepthook(typ, value, tb) |
| 152 |
except SystemExit: |
| 153 |
raise |
| 154 |
except BaseException as e: |
| 155 |
e.__context__ = None |
| 156 |
e = e.with_traceback(e.__traceback__.tb_next) |
| 157 |
print('Error in sys.excepthook:', file=sys.stderr) |
| 158 |
sys.__excepthook__(type(e), e, e.__traceback__) |
| 159 |
print(file=sys.stderr) |
| 160 |
print('Original exception was:', file=sys.stderr) |
| 161 |
sys.__excepthook__(typ, value, tb) |
| 162 |
|
| 163 |
def _excepthook(self, typ, value, tb): |
| 164 |
|
| 165 |
|
| 166 |
lines = traceback.format_exception(typ, value, tb) |
| 167 |
self.write(''.join(lines)) |
| 168 |
|
| 169 |
def write(self, data): |
| 170 |
"""Write a string. |
| 171 |
|
| 172 |
The base implementation writes to sys.stderr; a subclass may |
| 173 |
replace this with a different implementation. |
| 174 |
|
| 175 |
""" |
| 176 |
sys.stderr.write(data) |
| 177 |
|
| 178 |
|
| 179 |
class InteractiveConsole(InteractiveInterpreter): |
| 180 |
"""Closely emulate the behavior of the interactive Python interpreter. |
| 181 |
|
| 182 |
This class builds on InteractiveInterpreter and adds prompting |
| 183 |
using the familiar sys.ps1 and sys.ps2, and input buffering. |
| 184 |
|
| 185 |
""" |
| 186 |
|
| 187 |
def __init__(self, locals=None, filename="<console>"): |
| 188 |
"""Constructor. |
| 189 |
|
| 190 |
The optional locals argument will be passed to the |
| 191 |
InteractiveInterpreter base class. |
| 192 |
|
| 193 |
The optional filename argument should specify the (file)name |
| 194 |
of the input stream; it will show up in tracebacks. |
| 195 |
|
| 196 |
""" |
| 197 |
InteractiveInterpreter.__init__(self, locals) |
| 198 |
self.filename = filename |
| 199 |
self.resetbuffer() |
| 200 |
|
| 201 |
def resetbuffer(self): |
| 202 |
"""Reset the input buffer.""" |
| 203 |
self.buffer = [] |
| 204 |
|
| 205 |
def interact(self, banner=None, exitmsg=None): |
| 206 |
"""Closely emulate the interactive Python console. |
| 207 |
|
| 208 |
The optional banner argument specifies the banner to print |
| 209 |
before the first interaction; by default it prints a banner |
| 210 |
similar to the one printed by the real Python interpreter, |
| 211 |
followed by the current class name in parentheses (so as not |
| 212 |
to confuse this with the real interpreter -- since it's so |
| 213 |
close!). |
| 214 |
|
| 215 |
The optional exitmsg argument specifies the exit message |
| 216 |
printed when exiting. Pass the empty string to suppress |
| 217 |
printing an exit message. If exitmsg is not given or None, |
| 218 |
a default message is printed. |
| 219 |
|
| 220 |
""" |
| 221 |
try: |
| 222 |
sys.ps1 |
| 223 |
except AttributeError: |
| 224 |
sys.ps1 = ">>> " |
| 225 |
try: |
| 226 |
sys.ps2 |
| 227 |
except AttributeError: |
| 228 |
sys.ps2 = "... " |
| 229 |
cprt = 'Type "help", "copyright", "credits" or "license" for more information.' |
| 230 |
if banner is None: |
| 231 |
self.write("Python %s on %s\n%s\n(%s)\n" % |
| 232 |
(sys.version, sys.platform, cprt, |
| 233 |
self.__class__.__name__)) |
| 234 |
elif banner: |
| 235 |
self.write("%s\n" % str(banner)) |
| 236 |
more = 0 |
| 237 |
while 1: |
| 238 |
try: |
| 239 |
if more: |
| 240 |
prompt = sys.ps2 |
| 241 |
else: |
| 242 |
prompt = sys.ps1 |
| 243 |
try: |
| 244 |
line = self.raw_input(prompt) |
| 245 |
except EOFError: |
| 246 |
self.write("\n") |
| 247 |
break |
| 248 |
else: |
| 249 |
more = self.push(line) |
| 250 |
except KeyboardInterrupt: |
| 251 |
self.write("\nKeyboardInterrupt\n") |
| 252 |
self.resetbuffer() |
| 253 |
more = 0 |
| 254 |
if exitmsg is None: |
| 255 |
self.write('now exiting %s...\n' % self.__class__.__name__) |
| 256 |
elif exitmsg != '': |
| 257 |
self.write('%s\n' % exitmsg) |
| 258 |
|
| 259 |
def push(self, line): |
| 260 |
"""Push a line to the interpreter. |
| 261 |
|
| 262 |
The line should not have a trailing newline; it may have |
| 263 |
internal newlines. The line is appended to a buffer and the |
| 264 |
interpreter's runsource() method is called with the |
| 265 |
concatenated contents of the buffer as source. If this |
| 266 |
indicates that the command was executed or invalid, the buffer |
| 267 |
is reset; otherwise, the command is incomplete, and the buffer |
| 268 |
is left as it was after the line was appended. The return |
| 269 |
value is 1 if more input is required, 0 if the line was dealt |
| 270 |
with in some way (this is the same as runsource()). |
| 271 |
|
| 272 |
""" |
| 273 |
self.buffer.append(line) |
| 274 |
source = "\n".join(self.buffer) |
| 275 |
more = self.runsource(source, self.filename) |
| 276 |
if not more: |
| 277 |
self.resetbuffer() |
| 278 |
return more |
| 279 |
|
| 280 |
def raw_input(self, prompt=""): |
| 281 |
"""Write a prompt and read a line. |
| 282 |
|
| 283 |
The returned line does not include the trailing newline. |
| 284 |
When the user enters the EOF key sequence, EOFError is raised. |
| 285 |
|
| 286 |
The base implementation uses the built-in function |
| 287 |
input(); a subclass may replace this with a different |
| 288 |
implementation. |
| 289 |
|
| 290 |
""" |
| 291 |
return input(prompt) |
| 292 |
|
| 293 |
|
| 294 |
|
| 295 |
def interact(banner=None, readfunc=None, local=None, exitmsg=None): |
| 296 |
"""Closely emulate the interactive Python interpreter. |
| 297 |
|
| 298 |
This is a backwards compatible interface to the InteractiveConsole |
| 299 |
class. When readfunc is not specified, it attempts to import the |
| 300 |
readline module to enable GNU readline if it is available. |
| 301 |
|
| 302 |
Arguments (all optional, all default to None): |
| 303 |
|
| 304 |
banner -- passed to InteractiveConsole.interact() |
| 305 |
readfunc -- if not None, replaces InteractiveConsole.raw_input() |
| 306 |
local -- passed to InteractiveInterpreter.__init__() |
| 307 |
exitmsg -- passed to InteractiveConsole.interact() |
| 308 |
|
| 309 |
""" |
| 310 |
console = InteractiveConsole(local) |
| 311 |
if readfunc is not None: |
| 312 |
console.raw_input = readfunc |
| 313 |
else: |
| 314 |
try: |
| 315 |
import readline |
| 316 |
except ImportError: |
| 317 |
pass |
| 318 |
console.interact(banner, exitmsg) |
| 319 |
|
| 320 |
|
| 321 |
if __name__ == "__main__": |
| 322 |
import argparse |
| 323 |
|
| 324 |
parser = argparse.ArgumentParser() |
| 325 |
parser.add_argument('-q', action='store_true', |
| 326 |
help="don't print version and copyright messages") |
| 327 |
args = parser.parse_args() |
| 328 |
if args.q or sys.flags.quiet: |
| 329 |
banner = '' |
| 330 |
else: |
| 331 |
banner = None |
| 332 |
interact(banner) |