"""Utilities needed to emulate Python's interactive interpreter."""# Inspired by similar code by Jeff Epler and Fredrik Lundh.import sysimport tracebackfrom codeop import CommandCompiler, compile_command__all__ = ["InteractiveInterpreter", "InteractiveConsole", "interact","compile_command"]class InteractiveInterpreter:"""Base class for InteractiveConsole.This class deals with parsing and interpreter state (the user'snamespace); it doesn't deal with input buffering or prompting orinput file naming (the filename is always passed in explicitly)."""def __init__(self, locals=None):"""Constructor.The optional 'locals' argument specifies the dictionary inwhich code will be executed; it defaults to a newly createddictionary with key "__name__" set to "__console__" and key"__doc__" set to None."""if locals is None:locals = {"__name__": "__console__", "__doc__": None}self.locals = localsself.compile = CommandCompiler()def runsource(self, source, filename="<input>", symbol="single"):"""Compile and run some source in the interpreter.Arguments are as for compile_command().One several things can happen:1) The input is incorrect; compile_command() raised anexception (SyntaxError or OverflowError). A syntax tracebackwill be printed by calling the showsyntaxerror() method.2) The input is incomplete, and more input is required;compile_command() returned None. Nothing happens.3) The input is complete; compile_command() returned a codeobject. The code is executed by calling self.runcode() (whichalso handles run-time exceptions, except for SystemExit).The return value is True in case 2, False in the other cases (unlessan exception is raised). The return value can be used todecide whether to use sys.ps1 or sys.ps2 to prompt the nextline."""try:code = self.compile(source, filename, symbol)except (OverflowError, SyntaxError, ValueError):# Case 1self.showsyntaxerror(filename)return Falseif code is None:# Case 2return True# Case 3self.runcode(code)return Falsedef runcode(self, code):"""Execute a code object.When an exception occurs, self.showtraceback() is called todisplay a traceback. All exceptions are caught exceptSystemExit, which is reraised.A note about KeyboardInterrupt: this exception may occurelsewhere in this code, and may not always be caught. Thecaller should be prepared to deal with it."""try:exec(code, self.locals)except SystemExit:raiseexcept:self.showtraceback()def showsyntaxerror(self, filename=None):"""Display the syntax error that just occurred.This doesn't display a stack trace because there isn't one.If a filename is given, it is stuffed in the exception insteadof what was there before (because Python's parser always uses"<string>" when reading from a string).The output is written by self.write(), below."""type, value, tb = sys.exc_info()sys.last_type = typesys.last_value = valuesys.last_traceback = tbif filename and type is SyntaxError:# Work hard to stuff the correct filename in the exceptiontry:msg, (dummy_filename, lineno, offset, line) = value.argsexcept ValueError:# Not the format we expect; leave it alonepasselse:# Stuff in the right filenamevalue = SyntaxError(msg, (filename, lineno, offset, line))sys.last_value = valueif sys.excepthook is sys.__excepthook__:lines = traceback.format_exception_only(type, value)self.write(''.join(lines))else:# If someone has set sys.excepthook, we let that take precedence# over self.writesys.excepthook(type, value, tb)def showtraceback(self):"""Display the exception that just occurred.We remove the first stack item because it is our own code.The output is written by self.write(), below."""try:type, value, tb = sys.exc_info()sys.last_type = typesys.last_value = valuesys.last_traceback = tbtblist = traceback.extract_tb(tb)del tblist[:1]lines = traceback.format_list(tblist)if lines:lines.insert(0, "Traceback (most recent call last):\n")lines.extend(traceback.format_exception_only(type, value))finally:tblist = tb = Noneif sys.excepthook is sys.__excepthook__:self.write(''.join(lines))else:# If someone has set sys.excepthook, we let that take precedence# over self.writesys.excepthook(type, value, tb)def write(self, data):"""Write a string.The base implementation writes to sys.stderr; a subclass mayreplace this with a different implementation."""sys.stderr.write(data)class InteractiveConsole(InteractiveInterpreter):"""Closely emulate the behavior of the interactive Python interpreter.This class builds on InteractiveInterpreter and adds promptingusing the familiar sys.ps1 and sys.ps2, and input buffering."""def __init__(self, locals=None, filename="<console>"):"""Constructor.The optional locals argument will be passed to theInteractiveInterpreter base class.The optional filename argument should specify the (file)nameof the input stream; it will show up in tracebacks."""InteractiveInterpreter.__init__(self, locals)self.filename = filenameself.resetbuffer()def resetbuffer(self):"""Reset the input buffer."""self.buffer = []def interact(self, banner=None):"""Closely emulate the interactive Python console.The optional banner argument specifies the banner to printbefore the first interaction; by default it prints a bannersimilar to the one printed by the real Python interpreter,followed by the current class name in parentheses (so as notto confuse this with the real interpreter -- since it's soclose!)."""try:sys.ps1except AttributeError:sys.ps1 = ">>> "try:sys.ps2except AttributeError:sys.ps2 = "... "cprt = 'Type "help", "copyright", "credits" or "license" for more information.'if banner is None:self.write("Python %s on %s\n%s\n(%s)\n" %(sys.version, sys.platform, cprt,self.__class__.__name__))elif banner:self.write("%s\n" % str(banner))more = 0while 1:try:if more:prompt = sys.ps2else:prompt = sys.ps1try:line = self.raw_input(prompt)except EOFError:self.write("\n")breakelse:more = self.push(line)except KeyboardInterrupt:self.write("\nKeyboardInterrupt\n")self.resetbuffer()more = 0def push(self, line):"""Push a line to the interpreter.The line should not have a trailing newline; it may haveinternal newlines. The line is appended to a buffer and theinterpreter's runsource() method is called with theconcatenated contents of the buffer as source. If thisindicates that the command was executed or invalid, the bufferis reset; otherwise, the command is incomplete, and the bufferis left as it was after the line was appended. The returnvalue is 1 if more input is required, 0 if the line was dealtwith in some way (this is the same as runsource())."""self.buffer.append(line)source = "\n".join(self.buffer)more = self.runsource(source, self.filename)if not more:self.resetbuffer()return moredef raw_input(self, prompt=""):"""Write a prompt and read a line.The returned line does not include the trailing newline.When the user enters the EOF key sequence, EOFError is raised.The base implementation uses the built-in functioninput(); a subclass may replace this with a differentimplementation."""return input(prompt)def interact(banner=None, readfunc=None, local=None):"""Closely emulate the interactive Python interpreter.This is a backwards compatible interface to the InteractiveConsoleclass. When readfunc is not specified, it attempts to import thereadline module to enable GNU readline if it is available.Arguments (all optional, all default to None):banner -- passed to InteractiveConsole.interact()readfunc -- if not None, replaces InteractiveConsole.raw_input()local -- passed to InteractiveInterpreter.__init__()"""console = InteractiveConsole(local)if readfunc is not None:console.raw_input = readfuncelse:try:import readlineexcept ImportError:passconsole.interact(banner)if __name__ == "__main__":interact()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。
1. 开源生态
2. 协作、人、软件
3. 评估模型