# -*- coding: utf-8 -*-"""werkzeug.debug.console~~~~~~~~~~~~~~~~~~~~~~Interactive console support.:copyright: 2007 Pallets:license: BSD-3-Clause"""import codeimport sysfrom types import CodeTypefrom ..local import Localfrom ..utils import escapefrom .repr import debug_reprfrom .repr import dumpfrom .repr import helper_local = Local()class HTMLStringO(object):"""A StringO version that HTML escapes on write."""def __init__(self):self._buffer = []def isatty(self):return Falsedef close(self):passdef flush(self):passdef seek(self, n, mode=0):passdef readline(self):if len(self._buffer) == 0:return ""ret = self._buffer[0]del self._buffer[0]return retdef reset(self):val = "".join(self._buffer)del self._buffer[:]return valdef _write(self, x):if isinstance(x, bytes):x = x.decode("utf-8", "replace")self._buffer.append(x)def write(self, x):self._write(escape(x))def writelines(self, x):self._write(escape("".join(x)))class ThreadedStream(object):"""Thread-local wrapper for sys.stdout for the interactive console."""@staticmethoddef push():if not isinstance(sys.stdout, ThreadedStream):sys.stdout = ThreadedStream()_local.stream = HTMLStringO()@staticmethoddef fetch():try:stream = _local.streamexcept AttributeError:return ""return stream.reset()@staticmethoddef displayhook(obj):try:stream = _local.streamexcept AttributeError:return _displayhook(obj)# stream._write bypasses escaping as debug_repr is# already generating HTML for us.if obj is not None:_local._current_ipy.locals["_"] = objstream._write(debug_repr(obj))def __setattr__(self, name, value):raise AttributeError("read only attribute %s" % name)def __dir__(self):return dir(sys.__stdout__)def __getattribute__(self, name):if name == "__members__":return dir(sys.__stdout__)try:stream = _local.streamexcept AttributeError:stream = sys.__stdout__return getattr(stream, name)def __repr__(self):return repr(sys.__stdout__)# add the threaded stream as display hook_displayhook = sys.displayhooksys.displayhook = ThreadedStream.displayhookclass _ConsoleLoader(object):def __init__(self):self._storage = {}def register(self, code, source):self._storage[id(code)] = source# register code objects of wrapped functions too.for var in code.co_consts:if isinstance(var, CodeType):self._storage[id(var)] = sourcedef get_source_by_code(self, code):try:return self._storage[id(code)]except KeyError:passdef _wrap_compiler(console):compile = console.compiledef func(source, filename, symbol):code = compile(source, filename, symbol)console.loader.register(code, source)return codeconsole.compile = funcclass _InteractiveConsole(code.InteractiveInterpreter):def __init__(self, globals, locals):_locals = dict(globals)_locals.update(locals)locals = _localslocals["dump"] = dumplocals["help"] = helperlocals["__loader__"] = self.loader = _ConsoleLoader()code.InteractiveInterpreter.__init__(self, locals)self.more = Falseself.buffer = []_wrap_compiler(self)def runsource(self, source):source = source.rstrip() + "\n"ThreadedStream.push()prompt = "... " if self.more else ">>> "try:source_to_eval = "".join(self.buffer + [source])if code.InteractiveInterpreter.runsource(self, source_to_eval, "<debugger>", "single"):self.more = Trueself.buffer.append(source)else:self.more = Falsedel self.buffer[:]finally:output = ThreadedStream.fetch()return prompt + escape(source) + outputdef runcode(self, code):try:exec(code, self.locals)except Exception:self.showtraceback()def showtraceback(self):from .tbtools import get_current_tracebacktb = get_current_traceback(skip=1)sys.stdout._write(tb.render_summary())def showsyntaxerror(self, filename=None):from .tbtools import get_current_tracebacktb = get_current_traceback(skip=4)sys.stdout._write(tb.render_summary())def write(self, data):sys.stdout.write(data)class Console(object):"""An interactive console."""def __init__(self, globals=None, locals=None):if locals is None:locals = {}if globals is None:globals = {}self._ipy = _InteractiveConsole(globals, locals)def eval(self, code):_local._current_ipy = self._ipyold_sys_stdout = sys.stdouttry:return self._ipy.runsource(code)finally:sys.stdout = old_sys_stdout
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。