"""Extract, format and print information about Python stack traces."""import collectionsimport itertoolsimport linecacheimport sys__all__ = ['extract_stack', 'extract_tb', 'format_exception','format_exception_only', 'format_list', 'format_stack','format_tb', 'print_exc', 'format_exc', 'print_exception','print_last', 'print_stack', 'print_tb', 'clear_frames','FrameSummary', 'StackSummary', 'TracebackException','walk_stack', 'walk_tb']## Formatting and printing lists of traceback lines.#def print_list(extracted_list, file=None):"""Print the list of tuples as returned by extract_tb() orextract_stack() as a formatted stack trace to the given file."""if file is None:file = sys.stderrfor item in StackSummary.from_list(extracted_list).format():print(item, file=file, end="")def format_list(extracted_list):"""Format a list of tuples or FrameSummary objects for printing.Given a list of tuples or FrameSummary objects as returned byextract_tb() or extract_stack(), return a list of strings readyfor printing.Each string in the resulting list corresponds to the item with thesame index in the argument list. Each string ends in a newline;the strings may contain internal newlines as well, for those itemswhose source text line is not None."""return StackSummary.from_list(extracted_list).format()## Printing and Extracting Tracebacks.#def print_tb(tb, limit=None, file=None):"""Print up to 'limit' stack trace entries from the traceback 'tb'.If 'limit' is omitted or None, all entries are printed. If 'file'is omitted or None, the output goes to sys.stderr; otherwise'file' should be an open file or file-like object with a write()method."""print_list(extract_tb(tb, limit=limit), file=file)def format_tb(tb, limit=None):"""A shorthand for 'format_list(extract_tb(tb, limit))'."""return extract_tb(tb, limit=limit).format()def extract_tb(tb, limit=None):"""Return a StackSummary object representing a list ofpre-processed entries from traceback.This is useful for alternate formatting of stack traces. If'limit' is omitted or None, all entries are extracted. Apre-processed stack trace entry is a FrameSummary objectcontaining attributes filename, lineno, name, and linerepresenting the information that is usually printed for a stacktrace. The line is a string with leading and trailingwhitespace stripped; if the source is not available it is None."""return StackSummary.extract(walk_tb(tb), limit=limit)## Exception formatting and output.#_cause_message = ("\nThe above exception was the direct cause ""of the following exception:\n\n")_context_message = ("\nDuring handling of the above exception, ""another exception occurred:\n\n")def print_exception(etype, value, tb, limit=None, file=None, chain=True):"""Print exception up to 'limit' stack trace entries from 'tb' to 'file'.This differs from print_tb() in the following ways: (1) iftraceback is not None, it prints a header "Traceback (most recentcall last):"; (2) it prints the exception type and value after thestack trace; (3) if type is SyntaxError and value has theappropriate format, it prints the line where the syntax erroroccurred with a caret on the next line indicating the approximateposition of the error."""# format_exception has ignored etype for some time, and code such as cgitb# passes in bogus values as a result. For compatibility with such code we# ignore it here (rather than in the new TracebackException API).if file is None:file = sys.stderrfor line in TracebackException(type(value), value, tb, limit=limit).format(chain=chain):print(line, file=file, end="")def format_exception(etype, value, tb, limit=None, chain=True):"""Format a stack trace and the exception information.The arguments have the same meaning as the corresponding argumentsto print_exception(). The return value is a list of strings, eachending in a newline and some containing internal newlines. Whenthese lines are concatenated and printed, exactly the same text isprinted as does print_exception()."""# format_exception has ignored etype for some time, and code such as cgitb# passes in bogus values as a result. For compatibility with such code we# ignore it here (rather than in the new TracebackException API).return list(TracebackException(type(value), value, tb, limit=limit).format(chain=chain))def format_exception_only(etype, value):"""Format the exception part of a traceback.The arguments are the exception type and value such as given bysys.last_type and sys.last_value. The return value is a list ofstrings, each ending in a newline.Normally, the list contains a single string; however, forSyntaxError exceptions, it contains several lines that (whenprinted) display detailed information about where the syntaxerror occurred.The message indicating which exception occurred is always the laststring in the list."""return list(TracebackException(etype, value, None).format_exception_only())# -- not official API but folk probably use these two functions.def _format_final_exc_line(etype, value):valuestr = _some_str(value)if value is None or not valuestr:line = "%s\n" % etypeelse:line = "%s: %s\n" % (etype, valuestr)return linedef _some_str(value):try:return str(value)except:return '<unprintable %s object>' % type(value).__name__# --def print_exc(limit=None, file=None, chain=True):"""Shorthand for 'print_exception(*sys.exc_info(), limit, file)'."""print_exception(*sys.exc_info(), limit=limit, file=file, chain=chain)def format_exc(limit=None, chain=True):"""Like print_exc() but return a string."""return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))def print_last(limit=None, file=None, chain=True):"""This is a shorthand for 'print_exception(sys.last_type,sys.last_value, sys.last_traceback, limit, file)'."""if not hasattr(sys, "last_type"):raise ValueError("no last exception")print_exception(sys.last_type, sys.last_value, sys.last_traceback,limit, file, chain)## Printing and Extracting Stacks.#def print_stack(f=None, limit=None, file=None):"""Print a stack trace from its invocation point.The optional 'f' argument can be used to specify an alternatestack frame at which to start. The optional 'limit' and 'file'arguments have the same meaning as for print_exception()."""if f is None:f = sys._getframe().f_backprint_list(extract_stack(f, limit=limit), file=file)def format_stack(f=None, limit=None):"""Shorthand for 'format_list(extract_stack(f, limit))'."""if f is None:f = sys._getframe().f_backreturn format_list(extract_stack(f, limit=limit))def extract_stack(f=None, limit=None):"""Extract the raw traceback from the current stack frame.The return value has the same format as for extract_tb(). Theoptional 'f' and 'limit' arguments have the same meaning as forprint_stack(). Each item in the list is a quadruple (filename,line number, function name, text), and the entries are in orderfrom oldest to newest stack frame."""if f is None:f = sys._getframe().f_backstack = StackSummary.extract(walk_stack(f), limit=limit)stack.reverse()return stackdef clear_frames(tb):"Clear all references to local variables in the frames of a traceback."while tb is not None:try:tb.tb_frame.clear()except RuntimeError:# Ignore the exception raised if the frame is still executing.passtb = tb.tb_nextclass FrameSummary:"""A single frame from a traceback.- :attr:`filename` The filename for the frame.- :attr:`lineno` The line within filename for the frame that wasactive when the frame was captured.- :attr:`name` The name of the function or method that was executingwhen the frame was captured.- :attr:`line` The text from the linecache module for theof code that was running when the frame was captured.- :attr:`locals` Either None if locals were not supplied, or a dictmapping the name to the repr() of the variable."""__slots__ = ('filename', 'lineno', 'name', '_line', 'locals')def __init__(self, filename, lineno, name, *, lookup_line=True,locals=None, line=None):"""Construct a FrameSummary.:param lookup_line: If True, `linecache` is consulted for the sourcecode line. Otherwise, the line will be looked up when first needed.:param locals: If supplied the frame locals, which will be captured asobject representations.:param line: If provided, use this instead of looking up the line inthe linecache."""self.filename = filenameself.lineno = linenoself.name = nameself._line = lineif lookup_line:self.lineself.locals = {k: repr(v) for k, v in locals.items()} if locals else Nonedef __eq__(self, other):if isinstance(other, FrameSummary):return (self.filename == other.filename andself.lineno == other.lineno andself.name == other.name andself.locals == other.locals)if isinstance(other, tuple):return (self.filename, self.lineno, self.name, self.line) == otherreturn NotImplementeddef __getitem__(self, pos):return (self.filename, self.lineno, self.name, self.line)[pos]def __iter__(self):return iter([self.filename, self.lineno, self.name, self.line])def __repr__(self):return "<FrameSummary file {filename}, line {lineno} in {name}>".format(filename=self.filename, lineno=self.lineno, name=self.name)def __len__(self):return 4@propertydef line(self):if self._line is None:self._line = linecache.getline(self.filename, self.lineno).strip()return self._linedef walk_stack(f):"""Walk a stack yielding the frame and line number for each frame.This will follow f.f_back from the given frame. If no frame is given, thecurrent stack is used. Usually used with StackSummary.extract."""if f is None:f = sys._getframe().f_back.f_backwhile f is not None:yield f, f.f_linenof = f.f_backdef walk_tb(tb):"""Walk a traceback yielding the frame and line number for each frame.This will follow tb.tb_next (and thus is in the opposite order towalk_stack). Usually used with StackSummary.extract."""while tb is not None:yield tb.tb_frame, tb.tb_linenotb = tb.tb_next_RECURSIVE_CUTOFF = 3 # Also hardcoded in traceback.c.class StackSummary(list):"""A stack of frames."""@classmethoddef extract(klass, frame_gen, *, limit=None, lookup_lines=True,capture_locals=False):"""Create a StackSummary from a traceback or stack object.:param frame_gen: A generator that yields (frame, lineno) tuples toinclude in the stack.:param limit: None to include all frames or the number of frames toinclude.:param lookup_lines: If True, lookup lines for each frame immediately,otherwise lookup is deferred until the frame is rendered.:param capture_locals: If True, the local variables from each frame willbe captured as object representations into the FrameSummary."""if limit is None:limit = getattr(sys, 'tracebacklimit', None)if limit is not None and limit < 0:limit = 0if limit is not None:if limit >= 0:frame_gen = itertools.islice(frame_gen, limit)else:frame_gen = collections.deque(frame_gen, maxlen=-limit)result = klass()fnames = set()for f, lineno in frame_gen:co = f.f_codefilename = co.co_filenamename = co.co_namefnames.add(filename)linecache.lazycache(filename, f.f_globals)# Must defer line lookups until we have called checkcache.if capture_locals:f_locals = f.f_localselse:f_locals = Noneresult.append(FrameSummary(filename, lineno, name, lookup_line=False, locals=f_locals))for filename in fnames:linecache.checkcache(filename)# If immediate lookup was desired, trigger lookups now.if lookup_lines:for f in result:f.linereturn result@classmethoddef from_list(klass, a_list):"""Create a StackSummary object from a supplied list ofFrameSummary objects or old-style list of tuples."""# While doing a fast-path check for isinstance(a_list, StackSummary) is# appealing, idlelib.run.cleanup_traceback and other similar code may# break this by making arbitrary frames plain tuples, so we need to# check on a frame by frame basis.result = StackSummary()for frame in a_list:if isinstance(frame, FrameSummary):result.append(frame)else:filename, lineno, name, line = frameresult.append(FrameSummary(filename, lineno, name, line=line))return resultdef format(self):"""Format the stack ready for printing.Returns a list of strings ready for printing. Each string in theresulting list corresponds to a single frame from the stack.Each string ends in a newline; the strings may contain internalnewlines as well, for those items with source text lines.For long sequences of the same frame and line, the first fewrepetitions are shown, followed by a summary line stating the exactnumber of further repetitions."""result = []last_file = Nonelast_line = Nonelast_name = Nonecount = 0for frame in self:if (last_file is None or last_file != frame.filename orlast_line is None or last_line != frame.lineno orlast_name is None or last_name != frame.name):if count > _RECURSIVE_CUTOFF:count -= _RECURSIVE_CUTOFFresult.append(f' [Previous line repeated {count} more 'f'time{"s" if count > 1 else ""}]\n')last_file = frame.filenamelast_line = frame.linenolast_name = frame.namecount = 0count += 1if count > _RECURSIVE_CUTOFF:continuerow = []row.append(' File "{}", line {}, in {}\n'.format(frame.filename, frame.lineno, frame.name))if frame.line:row.append(' {}\n'.format(frame.line.strip()))if frame.locals:for name, value in sorted(frame.locals.items()):row.append(' {name} = {value}\n'.format(name=name, value=value))result.append(''.join(row))if count > _RECURSIVE_CUTOFF:count -= _RECURSIVE_CUTOFFresult.append(f' [Previous line repeated {count} more 'f'time{"s" if count > 1 else ""}]\n')return resultclass TracebackException:"""An exception ready for rendering.The traceback module captures enough attributes from the original exceptionto this intermediary form to ensure that no references are held, whilestill being able to fully print or format it.Use `from_exception` to create TracebackException instances from exceptionobjects, or the constructor to create TracebackException instances fromindividual components.- :attr:`__cause__` A TracebackException of the original *__cause__*.- :attr:`__context__` A TracebackException of the original *__context__*.- :attr:`__suppress_context__` The *__suppress_context__* value from theoriginal exception.- :attr:`stack` A `StackSummary` representing the traceback.- :attr:`exc_type` The class of the original traceback.- :attr:`filename` For syntax errors - the filename where the erroroccurred.- :attr:`lineno` For syntax errors - the linenumber where the erroroccurred.- :attr:`text` For syntax errors - the text where the erroroccurred.- :attr:`offset` For syntax errors - the offset into the text where theerror occurred.- :attr:`msg` For syntax errors - the compiler error message."""def __init__(self, exc_type, exc_value, exc_traceback, *, limit=None,lookup_lines=True, capture_locals=False, _seen=None):# NB: we need to accept exc_traceback, exc_value, exc_traceback to# permit backwards compat with the existing API, otherwise we# need stub thunk objects just to glue it together.# Handle loops in __cause__ or __context__.if _seen is None:_seen = set()_seen.add(id(exc_value))# Gracefully handle (the way Python 2.4 and earlier did) the case of# being called with no type or value (None, None, None).if (exc_value and exc_value.__cause__ is not Noneand id(exc_value.__cause__) not in _seen):cause = TracebackException(type(exc_value.__cause__),exc_value.__cause__,exc_value.__cause__.__traceback__,limit=limit,lookup_lines=False,capture_locals=capture_locals,_seen=_seen)else:cause = Noneif (exc_value and exc_value.__context__ is not Noneand id(exc_value.__context__) not in _seen):context = TracebackException(type(exc_value.__context__),exc_value.__context__,exc_value.__context__.__traceback__,limit=limit,lookup_lines=False,capture_locals=capture_locals,_seen=_seen)else:context = Noneself.exc_traceback = exc_tracebackself.__cause__ = causeself.__context__ = contextself.__suppress_context__ = \exc_value.__suppress_context__ if exc_value else False# TODO: locals.self.stack = StackSummary.extract(walk_tb(exc_traceback), limit=limit, lookup_lines=lookup_lines,capture_locals=capture_locals)self.exc_type = exc_type# Capture now to permit freeing resources: only complication is in the# unofficial API _format_final_exc_lineself._str = _some_str(exc_value)if exc_type and issubclass(exc_type, SyntaxError):# Handle SyntaxError's speciallyself.filename = exc_value.filenameself.lineno = str(exc_value.lineno)self.text = exc_value.textself.offset = exc_value.offsetself.msg = exc_value.msgif lookup_lines:self._load_lines()@classmethoddef from_exception(cls, exc, *args, **kwargs):"""Create a TracebackException from an exception."""return cls(type(exc), exc, exc.__traceback__, *args, **kwargs)def _load_lines(self):"""Private API. force all lines in the stack to be loaded."""for frame in self.stack:frame.lineif self.__context__:self.__context__._load_lines()if self.__cause__:self.__cause__._load_lines()def __eq__(self, other):return self.__dict__ == other.__dict__def __str__(self):return self._strdef format_exception_only(self):"""Format the exception part of the traceback.The return value is a generator of strings, each ending in a newline.Normally, the generator emits a single string; however, forSyntaxError exceptions, it emites several lines that (whenprinted) display detailed information about where the syntaxerror occurred.The message indicating which exception occurred is always the laststring in the output."""if self.exc_type is None:yield _format_final_exc_line(None, self._str)returnstype = self.exc_type.__qualname__smod = self.exc_type.__module__if smod not in ("__main__", "builtins"):stype = smod + '.' + stypeif not issubclass(self.exc_type, SyntaxError):yield _format_final_exc_line(stype, self._str)return# It was a syntax error; show exactly where the problem was found.filename = self.filename or "<string>"lineno = str(self.lineno) or '?'yield ' File "{}", line {}\n'.format(filename, lineno)badline = self.textoffset = self.offsetif badline is not None:yield ' {}\n'.format(badline.strip())if offset is not None:caretspace = badline.rstrip('\n')offset = min(len(caretspace), offset) - 1caretspace = caretspace[:offset].lstrip()# non-space whitespace (likes tabs) must be kept for alignmentcaretspace = ((c.isspace() and c or ' ') for c in caretspace)yield ' {}^\n'.format(''.join(caretspace))msg = self.msg or "<no detail available>"yield "{}: {}\n".format(stype, msg)def format(self, *, chain=True):"""Format the exception.If chain is not *True*, *__cause__* and *__context__* will not be formatted.The return value is a generator of strings, each ending in a newline andsome containing internal newlines. `print_exception` is a wrapper aroundthis method which just prints the lines to a file.The message indicating which exception occurred is always the laststring in the output."""if chain:if self.__cause__ is not None:yield from self.__cause__.format(chain=chain)yield _cause_messageelif (self.__context__ is not None andnot self.__suppress_context__):yield from self.__context__.format(chain=chain)yield _context_messageif self.exc_traceback is not None:yield 'Traceback (most recent call last):\n'yield from self.stack.format()yield from self.format_exception_only()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。