def getExceptionText(): """ create and return text of last exception """ _type, value, tback = sys.exc_info() frame_locals = {} if inspect.getinnerframes(tback) and inspect.getinnerframes(tback)[-1]: frame_locals = inspect.getinnerframes(tback)[-1][0].f_locals text = pprint.pformat(frame_locals) text += '\n' text += ''.join(traceback.format_exception(_type, value, tback)) return text
def get_exception_info(): # this variable is never used. it exists so we can detect if a frame is # referencing this specific function. __lgw_marker_local__ = 0 value_to_string = str frame_template = ' File "%s", line %i, in %s\n %s\n' log_file = [] # iterate through the frames in reverse order so we print the # most recent frame first frames = inspect.getinnerframes(sys.exc_info()[2]) for frame_info in reversed(frames): f_locals = frame_info[0].f_locals # if there's a local variable named __lgw_marker_local__, we assume # the frame is from a call of this function, 'wrapper', and we skip # it. Printing these frames won't help determine the cause of an # exception, so skipping it reduces clutter. if '__lgw_marker_local__' in f_locals: continue # log the frame information log_file.append(frame_template % (frame_info[1], frame_info[2], frame_info[3], frame_info[4][0].lstrip())) # log every local variable of the frame for k, v in f_locals.items(): log_file.append(' %s = %s\n' % (k, value_to_string(v))) log_file.append('\n') return ''.join(log_file)
def post_mortem(tb): import IPython stdout = sys.stdout try: sys.stdout = sys.__stdout__ if hasattr(IPython, 'InteractiveShell'): if hasattr(IPython.InteractiveShell, 'instance'): shell = IPython.InteractiveShell.instance() p = IPython.core.debugger.Pdb(shell.colors) else: shell = IPython.InteractiveShell() ip = IPython.core.ipapi.get() p = IPython.core.debugger.Pdb(ip.colors) # and keep support for older versions else: shell = IPython.Shell.IPShell(argv=['']) ip = IPython.ipapi.get() p = IPython.Debugger.Pdb(ip.options.colors) p.reset() # inspect.getinnerframes() returns a list of frames information # from this frame to the one that raised the exception being # treated frame, filename, line, func_name, ctx, idx = inspect.getinnerframes(tb)[-1] p.interaction(frame, tb) finally: sys.stdout = stdout
def debug(self, err): import IPython ec, ev, tb = err stdout = sys.stdout sys.stdout = sys.__stdout__ sys.stderr.write('\n- TRACEBACK --------------------------------------------------------------------\n') traceback.print_exception(*err) sys.stderr.write('--------------------------------------------------------------------------------\n') try: # The IPython API changed a bit so we should # support the new version if hasattr(IPython, 'InteractiveShell'): if hasattr(IPython.InteractiveShell, 'instance'): shell = IPython.InteractiveShell.instance() p = IPython.core.debugger.Pdb(shell.colors) else: shell = IPython.InteractiveShell() ip = IPython.core.ipapi.get() p = IPython.core.debugger.Pdb(ip.colors) # and keep support for older versions else: shell = IPython.Shell.IPShell(argv=['']) ip = IPython.ipapi.get() p = IPython.Debugger.Pdb(ip.options.colors) p.reset() # inspect.getinnerframes() returns a list of frames information # from this frame to the one that raised the exception being # treated frame, filename, line, func_name, ctx, idx = inspect.getinnerframes(tb)[-1] p.interaction(frame, tb) finally: sys.stdout = stdout
def debug(self, err): import IPython ec, ev, tb = err # This is to work around issue #16, that occured when the exception # value was being passed as a string. if isinstance(ev, str): ev = ec(ev) stdout = sys.stdout sys.stdout = sys.__stdout__ sys.stderr.write('\n- TRACEBACK --------------------------------------------------------------------\n') traceback.print_exception(ec, ev, tb) sys.stderr.write('--------------------------------------------------------------------------------\n') try: from IPython.terminal.ipapp import TerminalIPythonApp app = TerminalIPythonApp.instance() app.initialize(argv=['--no-banner']) try: # ipython >= 5.0 p = IPython.terminal.debugger.TerminalPdb(app.shell.colors) except AttributeError: p = IPython.core.debugger.Pdb(app.shell.colors) p.reset() # inspect.getinnerframes() returns a list of frames information # from this frame to the one that raised the exception being # treated frame, filename, line, func_name, ctx, idx = inspect.getinnerframes(tb)[-1] p.interaction(frame, tb) finally: sys.stdout = stdout
def _fixed_getframes(etb, context=1, tb_offset=0): LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) # If the error is at the console, don't build any context, since it would # otherwise produce 5 blank lines printed out (there is no file at the # console) rec_check = records[tb_offset:] try: rname = rec_check[0][1] if rname == '<ipython console>' or rname.endswith('<string>'): return rec_check except IndexError: pass aux = traceback.extract_tb(etb) assert len(records) == len(aux) for i, (file, lnum, _, _) in enumerate(aux): maybeStart = lnum - 1 - context // 2 start = max(maybeStart, 0) end = start + context lines = linecache.getlines(file)[start:end] # pad with empty lines if necessary if maybeStart < 0: lines = (['\n'] * -maybeStart) + lines if len(lines) < context: lines += ['\n'] * (context - len(lines)) buf = list(records[i]) buf[LNUM_POS] = lnum buf[INDEX_POS] = lnum - 1 - start buf[LINES_POS] = lines records[i] = tuple(buf) return records[tb_offset:]
def _fixed_getinnerframes(etb, context=1, tb_offset=0): import linecache LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) # If the error is at the console, don't build any context, since it would # otherwise produce 5 blank lines printed out (there is no file at the # console) rec_check = records[tb_offset:] try: rname = rec_check[0][1] if rname == "<ipython console>" or rname.endswith("<string>"): return rec_check except IndexError: pass aux = traceback.extract_tb(etb) assert len(records) == len(aux) for i, (file, lnum, _, _) in zip(range(len(records)), aux): maybeStart = lnum - 1 - context // 2 start = max(maybeStart, 0) end = start + context lines = linecache.getlines(file)[start:end] buf = list(records[i]) buf[LNUM_POS] = lnum buf[INDEX_POS] = lnum - 1 - start buf[LINES_POS] = lines records[i] = tuple(buf) return records[tb_offset:]
def __init__(self, exc_type, exc_value, exc_traceback, options): self.className = exc_type.__name__ self.message = "%s: %s" % (exc_type.__name__, exc_value) self.stackTrace = [] if "transmitGlobalVariables" in options and options["transmitGlobalVariables"] is True: self.globalVariables = globals() frames = None try: frames = inspect.getinnerframes(exc_traceback) if frames: for frame in frames: self.stackTrace.append( { "lineNumber": frame[2], "className": frame[3], "fileName": frame[1], "methodName": frame[4][0] if frame[4] is not None else None, "localVariables": self._get_locals(frame[0]) if "transmitLocalVariables" in options and options["transmitLocalVariables"] is True else None, } ) finally: del frames self.data = ""
def analyse(exctyp, value, tb): import tokenize, keyword trace = StringIO() nlines = 3 frecs = inspect.getinnerframes(tb, nlines) trace.write("Traceback (most recent call last):\n") for frame, fname, lineno, funcname, context, cindex in frecs: trace.write(' File "%s", line %d, ' % (fname, lineno)) args, varargs, varkw, lcls = inspect.getargvalues(frame) def readline(lno=[lineno], *args): if args: print(args) try: return linecache.getline(fname, lno[0]) finally: lno[0] += 1 all, prev, name, scope = {}, None, "", None for ttype, tstr, stup, etup, line in tokenize.generate_tokens(readline): if ttype == tokenize.NAME and tstr not in keyword.kwlist: if name: if name[-1] == ".": try: val = getattr(prev, tstr) except AttributeError: # XXX skip the rest of this identifier only break name += tstr else: assert not name and not scope scope, val = lookup(tstr, frame, lcls) name = tstr if hasattr(val, "shape") and len(val): prev = val elif val: prev = val # print ' found', scope, 'name', name, 'val', val, 'in', prev, 'for token', tstr elif tstr == ".": if prev: name += "." else: if name: all[name] = (scope, prev) prev, name, scope = None, "", None if ttype == tokenize.NEWLINE: break trace.write( funcname + inspect.formatargvalues(args, varargs, varkw, lcls, formatvalue=lambda v: "=" + pydoc.text.repr(v)) + "\n" ) trace.write("".join([" " + x.replace("\t", " ") for x in [a for a in context if a.strip()]])) if len(all): trace.write(" variables: %s\n" % str(all)) trace.write("%s: %s" % (exctyp.__name__, value)) return trace
def _add_exception_info(self, data, record): """Adds sentry interfaces Exception and Stacktrace. See http://sentry.readthedocs.org/en/latest/developer/interfaces/index.html for more information on Sentry interfaces.""" type_, value, tb = record.exc_info data[SENTRY_INTERFACES_EXCEPTION] = {"type": str(type_), "value": str(value), "module": record.module } stack = inspect.getinnerframes(tb) # This next python statement copied pretty much verbatim from # raven-python (https://github.com/getsentry/raven-python). # # raven-python is: # # Copyright (c) 2009 David Cramer and individual contributors. # All rights reserved. frames = varmap( lambda k, v: shorten( v, string_length=self.string_max_length, list_length=self.list_max_length), get_stack_info(iter_stack_frames(stack))) # end of copied code data['sentry.interfaces.Stacktrace'] = { 'frames': frames } return data
def debug_exceptions(type, value, tb): base_name = "dump" # find a browser object in the stack frames = inspect.getinnerframes(tb) frames.reverse() # reversed because we want the innermost first browser = None for frame, _, _, _, _, _ in frames: for v in inspect.getargvalues(frame).locals.values(): if isinstance(v, Browser): browser = v break localest = frames[0][0] # stick a trace in a file with open(base_name + '.trace', 'w') as tracefile: tracefile.write("Locals:\n") pprint(localest.f_locals, tracefile) tracefile.write("\n") if browser is not None: tracefile.write("URL: %s\n" % browser.url) tracefile.write("\n") traceback.print_tb(tb, file=tracefile) if browser is not None: browser.save(base_name + '.html') # then call the default handler sys.__excepthook__(type, value, tb)
def RunWithExpandedTrace(closure): try: return closure() except (SystemExit, KeyboardInterrupt): raise except: import inspect import sys import traceback # Save trace and exception now. This call looks at the most recently # raised exception. The code that makes the report might trigger other # exceptions. exc_type, exc_value, tb = sys.exc_info() frame_records = inspect.getinnerframes(tb, 3)[1:] formatted_exception = traceback.format_exception_only(exc_type, exc_value) dashes = '%s\n' % ('-' * 60) dump = [] dump.append(dashes) dump.extend(MakeExpandedTrace(frame_records)) dump.append(''.join(formatted_exception)) print(''.join(dump)) print() print(dashes) sys.exit(127)
def critical(message, title="Critical", include_stack_trace=True, **kwargs): """ Logs a new critical message with all loggers. :param message: The message of the log entry. :param title: A title for the entry. :param include_stack_trace: If this function is called from within an exception, should a stack trace be printed? :param kwargs: Key-word arguments. These are inserted in the message body. The value of a key-word argument will be put in place of the key surrounded by brackets. See the Python documentation for ``str.format`` for more details. """ substituted = message.format(**kwargs) #Substitute all arguments into the message. loggers = luna.plugins.plugins_by_type["logger"] stack_trace = [] exception = None if include_stack_trace: traceback = sys.exc_info()[2] if traceback: stack_trace = list(reversed(inspect.getouterframes(traceback.tb_frame)[1:])) + inspect.getinnerframes(traceback) exception = sys.exc_info()[1] for logger in loggers: if Level.CRITICAL in _logger_levels[logger]: loggers[logger]["logger"]["critical"](substituted, title, stack_trace, exception) if not loggers: #There are no loggers. if title != "Critical": #The word "Critical" is already put there by the logger. substituted = title + ": " + substituted if include_stack_trace and sys.exc_info()[2]: logging.exception(substituted) else: logging.critical(substituted)
def debug(message, title="Debug", include_stack_trace=True, **kwargs): """ Logs a new debug message with all loggers. :param message: The message of the log entry. :param title: A title for the entry. :param include_stack_trace: If this function is called from within an exception, should a stack trace be printed? :param kwargs: Key-word arguments. These are inserted in the message body. The value of a key-word argument will be put in place of the key surrounded by brackets. See the Python documentation for ``str.format`` for more details. """ substituted = message.format(**kwargs) #Substitute all arguments into the message. loggers = luna.plugins.plugins_by_type["logger"] stack_trace = [] exception = None if include_stack_trace: traceback = sys.exc_info()[2] if traceback: stack_trace = list(reversed(inspect.getouterframes(traceback.tb_frame)[1:])) + inspect.getinnerframes(traceback) exception = sys.exc_info()[1] for logger in loggers: if Level.DEBUG in _logger_levels[logger]: loggers[logger]["logger"]["debug"](substituted, title, stack_trace, exception)
def _fixed_getinnerframes(etb, context=1,tb_offset=0): import linecache LNUM_POS, LINES_POS, INDEX_POS = 2, 4, 5 records = fix_frame_records_filenames(inspect.getinnerframes(etb, context)) rec_check = records[tb_offset:] try: rname = rec_check[0][1] if rname == '<ipython console>' or rname.endswith('<string>'): return rec_check except IndexError: pass aux = traceback.extract_tb(etb) assert len(records) == len(aux) for i, (file, lnum, _, _) in zip(range(len(records)), aux): maybeStart = lnum-1 - context//2 start = max(maybeStart, 0) end = start + context lines = linecache.getlines(file)[start:end] # pad with empty lines if necessary if maybeStart < 0: lines = (['\n'] * -maybeStart) + lines if len(lines) < context: lines += ['\n'] * (context - len(lines)) buf = list(records[i]) buf[LNUM_POS] = lnum buf[INDEX_POS] = lnum - 1 - start buf[LINES_POS] = lines records[i] = tuple(buf) return records[tb_offset:]
def wrapper(*args, **kwargs): try: return f(*args, **kwargs) except handled_exceptions: if not handler: return if not var_names: return handler() frames = inspect.getinnerframes(sys.exc_info()[2]) values = {} names = var_names.split(",") for frame in reversed(frames): f_locals = frame[0].f_locals for name in names[:]: if name in f_locals: values[name] = f_locals[name] names.remove(name) if len(names) == 0: break else: assert False, "local variable(s) '{}' not found".format( ",".join(names)) return apply_function(handler, values, *xargs, **xkwargs)
def exception ( self, type, value, traceback, msg = '', offset = 0, debug_frame = None ): """ Handles a program exception or break point. """ # Get the correct status message and execution frames: if value is None: msg = msg or 'Called the FBI' frames = [ StackFrame( frame ) for frame in stack( 15 )[ offset + 2: ] ] else: msg = 'Exception: %s' % str( value ) frames = [ StackFrame( frame ) for frame in getinnerframes( traceback, 15 ) ] frames.reverse() frames.extend( [ StackFrame( frame ) for frame in stack( 15 )[3:] ] ) # Make sure we don't handle and more exceptions for the moment: self.enabled = False # Set the new debugging context data: self.msg = msg self.frames = frames self.debug_frame = debug_frame # Activate the user interface containing all of the debugger tools: self.tools.activate() # Stop execution here until the developer resumes execution: self.active = True toolkit().event_loop() self.active = False # Resume execution and re-enable the debugger: self.enabled = (not self.has_quit)
def get_error_snapshot(depth=5): """Return a dict describing a given traceback (based on cgitb.text).""" etype, evalue, etb = sys.exc_info() if isinstance(etype, type): etype = etype.__name__ data = {} data['timestamp'] = datetime.datetime.utcnow().isoformat() data['python_version'] = sys.version platform_keys = [ 'machine', 'node', 'platform', 'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation', 'python_revision', 'python_version', 'python_version_tuple', 'release', 'system', 'uname', 'version'] data['platform_info'] = {key: getattr(platform, key)() for key in platform_keys} data['os_environ'] = {key: str(value) for key, value in os.environ.items()} data['traceback'] = traceback.format_exc() data['exception_type'] = str(etype) data['exception_value'] = str(evalue) # loopover the stack frames items = inspect.getinnerframes(etb, depth) del etb # Prevent circular references that would cause memory leaks data['stackframes'] = stackframes = [] for frame, file, lnum, func, lines, index in items: file = file and os.path.abspath(file) or '?' args, varargs, varkw, locals = inspect.getargvalues(frame) # basic frame information f = {'file': file, 'func': func, 'lnum': lnum} f['code'] = lines line_vars = cgitb.scanvars(lambda: linecache.getline(file, lnum), frame, locals) # dump local variables (referenced in current line only) f['vars'] = {key: str(value) for key, value in locals.items() if not key.startswith('__')} stackframes.append(f) return data
def exceptHook(*args): '''A routine to be called when an exception occurs. It prints the traceback with fancy formatting and then calls an IPython shell with the environment of the exception location. This routine is only used when debug=True is set in config.py ''' from IPython.core import ultratb if 'win' in sys.platform: ultratb.FormattedTB(call_pdb=False,color_scheme='NoColor')(*args) else: ultratb.FormattedTB(call_pdb=False,color_scheme='LightBG')(*args) try: from IPython.terminal.embed import InteractiveShellEmbed except ImportError: try: # try the IPython 0.12 approach from IPython.frontend.terminal.embed import InteractiveShellEmbed except ImportError: print 'IPython InteractiveShellEmbed not found' return import inspect frame = inspect.getinnerframes(args[2])[-1][0] msg = 'Entering IPython console at {0.f_code.co_filename} at line {0.f_lineno}'.format(frame) savehook = sys.excepthook # save the exception hook InteractiveShellEmbed(banner1=msg)(local_ns=frame.f_locals,global_ns=frame.f_globals) sys.excepthook = savehook # reset IPython's change to the exception hook
def main(): globs = {} try: #doctest.testmod() doctest.testmod(raise_on_error=True, globs=globs) except doctest.UnexpectedException as failure: exc_info = failure.exc_info # ctx = {} # for example in failure.test.examples: # try: # exec example.source in ctx, globals() # except Exception, e: # pm_to.__startframe__ = exc_info[2] # TODO: fuzzy? find functions on the same module that # were modified "soon" raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) except doctest.DocTestFailure as failure: example = failure.example print(example.source, '?=', example.want, 'got', failure.got, file=sys.stderr) try: # globs = {} # for ex in failure.test.examples: # if ex is example: break # exec ex.source in globs, globals() assert eval(example.source, globs, globals()) == eval(example.want, globs, globals()) except AssertionError: pm_to.__frames__ = [tb for tb in inspect.getinnerframes(sys.exc_info()[2])] calls = [i for i in ast.walk(ast.parse(failure.example.source)) if isinstance(i, ast.Call)] if len(calls) > 0: _, fname = calls[-1], calls[-1].func.id print('on call ', fname, 'locals are', pm_to(fname), file=sys.stderr)
def _format_trace(self, traceback_obj=None, levels=2): """ Builds a nicely formatted stack trace as a list of frame data. :param tb: optional traceback object :param levels: optional caller levels to ignore when autogenerating traceback (if tb is None) :returns: a list of [frameNo, moduleName, formattedString] entries """ if traceback_obj: frames = inspect.getinnerframes(traceback_obj) else: frames = inspect.stack()[levels:] # skip this and its caller trace = [] frameNo = 0 for frame, _, line, function, src, pos in frames: code = src[pos].strip() if pos >= 0 else '(no source)' name = self.get_frame_name(frame) if function == '?': prettyargs = '' else: prettyargs = self._format_args(frame) # here we could separate words in "code" and try to match them in # frame.f_locals so we can display the variables involved there. trace.append((frameNo, name, "%s%s at line %d: %s" % (function, prettyargs, line, code))) frameNo += 1 return trace
def format_exception_locals(information=None, ignore_builtins=True, caption=None, indent="", filler=DEFAULT_FILLER, into=None): lines = [] if into is None else into extype, exvalue, extraceback = information or sys.exc_info() frame = inspect.getinnerframes(extraceback)[-1][0] if caption: lines.append(indent + caption) indent += settings.LOGGING_INDENT for name, value in frame.f_locals.iteritems(): caption = align(name, NAME_WIDTH - len(indent), " ", filler=filler) if ignore_builtins and name == "__builtins__": description = "{...}" else: try: description = represent( value, width=VALUE_WIDTH).replace("\n", "\n%s%s" % ("", NAME_WIDTH * " ")) except Exception as error: try: message = str(error) except Exception: message = type(error).__name__ description = "Unable to represent: %s" % message lines.append("%s%s%s" % (indent, caption, description)) if into is None: lines.append("") return "\n".join(lines)
def __init__(self, exc_type, exc_value, exc_traceback, options): self.className = exc_type.__name__ self.message = "%s: %s" % (exc_type.__name__, exc_value) self.stackTrace = [] try: frames = inspect.getinnerframes(exc_traceback) if frames: for frame in frames: self.stackTrace.append({ 'lineNumber': frame[2], 'className': frame[3], 'fileName': frame[1], 'methodName': frame[4][0] if frame[4] is not None else None, 'localVariables': self._get_locals(frame[0]) if 'transmitLocalVariables' in options and options['transmitLocalVariables'] is True else None }) if 'transmitGlobalVariables' in options and options['transmitGlobalVariables'] is True and len(frames) > 0: self.globalVariables = frames[-1][0].f_globals finally: del frames self.data = "" if isinstance(exc_value, Exception): nestedException = None if exc_value.__cause__: nestedException = exc_value.__cause__ elif exc_value.__context__: nestedException = exc_value.__context__ if nestedException is not None: self.innerError = RaygunErrorMessage(type(nestedException), nestedException, nestedException.__traceback__, options)
def analyze (self, exctyp, value, tb): """ Analyzes the exception into a human readable stack trace """ import tokenize, keyword trace = StringIO() nlines = 3 frecs = inspect.getinnerframes (tb, nlines) trace.write ('Traceback (most recent call last):\n') for frame, fname, lineno, funcname, context, cindex in frecs: trace.write (' File "%s", line %d, ' % (fname, lineno)) args, varargs, varkw, lcls = inspect.getargvalues (frame) def readline (lno=[lineno], *args): if args: print args try: return linecache.getline (fname, lno[0]) finally: lno[0] += 1 all, prev, name, scope = {}, None, '', None for ttype, tstr, stup, etup, line in tokenize.generate_tokens (readline): if ttype == tokenize.NAME and tstr not in keyword.kwlist: if name: if name[-1] == '.': try: val = getattr (prev, tstr) except AttributeError: # XXX skip the rest of this identifier only break name += tstr else: assert not name and not scope scope, val = self.lookup(tstr, frame, lcls) name = tstr if val is not None: prev = val elif tstr == '.': if prev: name += '.' else: if name: all[name] = (scope, prev) prev, name, scope = None, '', None if ttype == tokenize.NEWLINE: break try: details = inspect.formatargvalues (args, varargs, varkw, lcls, formatvalue=lambda v: '=' + pydoc.text.repr (v)) except: # seen that one on Windows (actual exception was KeyError: self) details = '(no details)' trace.write (funcname + details + '\n') if context is None: context = ['<source context missing>\n'] trace.write (''.join ([' ' + x.replace ('\t', ' ') for x in filter (lambda a: a.strip(), context)])) if len (all): trace.write (' variables: %s\n' % str (all)) trace.write ('%s: %s' % (exctyp.__name__, value)) return trace
def extract_traceback(tb, context=1): frames = inspect.getinnerframes(tb, context) for frame, filename, lineno, function, code_context, index in frames: formatted_args, cls = _get_frame_args(frame) if cls: function = '%s.%s' % (cls, function) yield TracebackEntry(filename, lineno, function, formatted_args, code_context, index)
def tracebackFrames(self, info): frames = [] traceback = info[2] for record in inspect.getinnerframes(traceback, self.context): frame = self.frameClass(*record) frames.append(frame.format(self.formatter)) del traceback return frames
def text(einfo, context = 5): """Return a plain text document describing a given traceback.""" etype, evalue, etb = einfo if type(etype) is types.ClassType: etype = etype.__name__ pyver = 'Python ' + sys.version.split()[0] + ': ' + sys.executable date = time.ctime(time.time()) head = '%s\n%s\n%s\n' % (str(etype), pyver, date) + '\nA problem occurred in a Python script. Here is the sequence of\nfunction calls leading up to the error, in the order they occurred.\n' frames = [] records = inspect.getinnerframes(etb, context) for frame, file, lnum, func, lines, index in records: file = file and os.path.abspath(file) or '?' args, varargs, varkw, locals = inspect.getargvalues(frame) call = '' if func != '?': call = 'in ' + func + inspect.formatargvalues(args, varargs, varkw, locals, formatvalue=lambda value: '=' + pydoc.text.repr(value)) highlight = {} def reader(lnum = [lnum]): highlight[lnum[0]] = 1 try: return linecache.getline(file, lnum[0]) finally: lnum[0] += 1 vars = scanvars(reader, frame, locals) rows = [' %s %s' % (file, call)] if index is not None: i = lnum - index for line in lines: num = '%5d ' % i rows.append(num + line.rstrip()) i += 1 done, dump = {}, [] for name, where, value in vars: if name in done: continue done[name] = 1 if value is not __UNDEF__: if where == 'global': name = 'global ' + name elif where != 'local': name = where + name.split('.')[-1] dump.append('%s = %s' % (name, pydoc.text.repr(value))) else: dump.append(name + ' undefined') rows.append('\n'.join(dump)) frames.append('\n%s\n' % '\n'.join(rows)) exception = ['%s: %s' % (str(etype), str(evalue))] if isinstance(evalue, BaseException): for name in dir(evalue): value = pydoc.text.repr(getattr(evalue, name)) exception.append('\n%s%s = %s' % (' ', name, value)) return head + ''.join(frames) + ''.join(exception) + '\n\nThe above is a description of an error in a Python program. Here is\nthe original traceback:\n\n%s\n' % ''.join(traceback.format_exception(etype, evalue, etb))
def get_frame_from_traceback(traceback, frame_number): ''' Returns n-th frame object from traceback. Returns None, if traceback doesn't have frame with such number. ''' frames = inspect.getinnerframes(traceback) try: return frames[frame_number][0] except IndexError: return None
def analyse(exctyp, value, tb): import tokenize, keyword trace = StringIO() nlines = 3 frecs = inspect.getinnerframes(tb, nlines) trace.write('Traceback (most recent call last):\n') for frame, fname, lineno, funcname, context, cindex in frecs: trace.write(' File "%s", line %d, ' % (fname, lineno)) args, varargs, varkw, lcls = inspect.getargvalues(frame) def readline(lno=[lineno], *args): if args: print args try: return linecache.getline(fname, lno[0]) finally: lno[0] += 1 all, prev, name, scope = {}, None, '', None for ttype, tstr, stup, etup, line in tokenize.generate_tokens(readline): if ttype == tokenize.NAME and tstr not in keyword.kwlist: if name: if name[-1] == '.': try: val = getattr(prev, tstr) except AttributeError: # XXX skip the rest of this identifier only break name += tstr else: assert not name and not scope scope, val = lookup(tstr, frame, lcls) name = tstr try: if val: prev = val except: pass #print ' found', scope, 'name', name, 'val', val, 'in', prev, 'for token', tstr elif tstr == '.': if prev: name += '.' else: if name: all[name] = (scope, prev) prev, name, scope = None, '', None if ttype == tokenize.NEWLINE: break trace.write(funcname + inspect.formatargvalues(args, varargs, varkw, lcls, formatvalue=lambda v: '=' + pydoc.text.repr(v)) + '\n') trace.write(''.join([' ' + x.replace('\t', ' ') for x in filter(lambda a: a.strip(), context)])) if len(all): trace.write(' variables: %s\n' % pformat(all, indent=3)) trace.write('%s: %s' % (exctyp.__name__, value)) return trace
def FormatException(exctype, value, tb, length=None): frame_records = inspect.getinnerframes(tb, 3) dump = [] if length is None: dump.extend(traceplus.MakeExpandedTrace(frame_records)) else: dump.extend(traceplus.MakeExpandedTrace(frame_records[:length])) dump.extend(traceback.format_exception_only(exctype, value)) return ''.join(dump)
def reraise(original, exception): prev_cls, prev, tb = sys.exc_info() frames = inspect.getinnerframes(tb) if len(frames) > 1: exception = original try: raise exception.with_traceback(tb) except AttributeError: # This syntax is not a valid Python 3 syntax so we have # to work around that exec('raise exception.__class__, exception, tb')
def info(type, value, tb): traceback.print_exception(type, value, tb) print() # Insert look-around helpers into the frame import inspect, ast from .asttools import to_source frame = inspect.getinnerframes(tb)[-1][0] frame.f_globals.setdefault('ast', ast) frame.f_globals.setdefault('to_source', to_source) # Run debugger ipdb.pm()
def get_records(self, tb): """Get the traceback frame history, excluding those originating from our own code that are included either at the beginning or at the end of the traceback. """ records = inspect.getinnerframes(tb, cache.context) records = list( dropwhile(lambda record: is_excluded_file(record.filename), records)) records.reverse() records = list( dropwhile(lambda record: is_excluded_file(record.filename), records)) records.reverse() # If all the records are removed, it means that all the error # is in our own code - or that of the user who chose to exclude # some files. If so, we make sure to have something to analyze # and help identify the problem. if not records and not issubclass(self.exception_type, SyntaxError): return inspect.getinnerframes(tb, cache.context) return records
def getBacktraceDetailed(self, tracebackObject=""): """ Get stackframe log is a very detailed log with filepaths, code locations & global vars, this output can become quite big """ import inspect if j.application.skipTraceback: return "" sep = "\n" + "-" * 90 + "\n" result = '' if not tracebackObject: return "" #@todo needs to be fixed so it does work if tracebackObject == None: tracebackObject = inspect.currentframe() #@todo does not work frames = inspect.getinnerframes(tracebackObject, 16) nrlines = 0 for (frame, filename, lineno, fun, context, idx) in frames: ##result = result + "-"*50 + "\n\n" nrlines += 1 if nrlines > 100: return result location = filename + "(line %d) (function %s)\n" % (lineno, fun) if location.find("EventHandler.py") == -1: result += " " + sep result += " " + location result += " " + "========== STACKFRAME==========\n" if context: l = 0 for line in context: prefix = " " if l == idx: prefix = "--> " l += 1 result += prefix + line nrlines += 1 if nrlines > 100: return result result += " " + "============ LOCALS============\n" for (k, v) in sorted(frame.f_locals.iteritems()): if self._filterLocals(k, v): try: result += " %s : %s\n" % (str(k), str(v)) except: pass nrlines += 1 if nrlines > 100: return result ##result += " " + "============ GLOBALS============\n" ##for (k,v) in sorted(frame.f_globals.iteritems()): ## if self._filterLocals(k,v): ## result += " %s : %s\n" % (str(k), str(v)) self.backtrace = result
def get_frame_locals(): traceback = sys.exc_info()[2] if traceback: frames = inspect.getinnerframes(traceback, context=0) _locals = ['Locals (most recent call last):'] for frame, filename, lineno, function, __, __ in frames: if '/apps/' in filename: _locals.append('File "{}", line {}, in {}\n{}'.format( filename, lineno, function, json.dumps(frame.f_locals, default=str, indent=4))) return '\n'.join(_locals)
def getInnerMostFrame(trcback): """ Returns the inner most frame of given traceback. :param trcback: Traceback. :type trcback: Traceback :return: Frame. :rtype: Frame """ frames = inspect.getinnerframes(trcback) return frames.pop()[0] if frames else None
def analyse (exctyp, value, tb): import tokenize, keyword trace = StringIO() nlines = 3 frecs = inspect.getinnerframes (tb, nlines) trace.write ('Traceback (most recent call last):\n') for frame, fname, lineno, funcname, context, cindex in frecs: trace.write (' File "%s", line %d, ' % (fname, lineno)) args, varargs, varkw, lcls = inspect.getargvalues (frame) def readline (lno=[lineno], *args): if args: print args try: return linecache.getline (fname, lno[0]) finally: lno[0] += 1 all, prev, name, scope = {}, None, '', None for ttype, tstr, stup, etup, line in tokenize.generate_tokens (readline): if ttype == tokenize.NAME and tstr not in keyword.kwlist: if name: if name[-1] == '.': try: val = getattr (prev, tstr) except AttributeError: # XXX skip the rest of this identifier only break name += tstr else: assert not name and not scope scope, val = lookup (tstr, frame, lcls) name = tstr if hasattr(val, "shape") and len(val): prev = val elif val: prev = val #print ' found', scope, 'name', name, 'val', val, 'in', prev, 'for token', tstr elif tstr == '.': if prev: name += '.' else: if name: all[name] = (scope, prev) prev, name, scope = None, '', None if ttype == tokenize.NEWLINE: break trace.write (funcname + inspect.formatargvalues (args, varargs, varkw, lcls, formatvalue=lambda v: '=' + pydoc.text.repr (v)) + '\n') trace.write (''.join ([' ' + x.replace ('\t', ' ') for x in filter (lambda a: a.strip(), context)])) if len (all): trace.write (' variables: %s\n' % str (all)) trace.write ('%s: %s' % (exctyp.__name__, value)) return trace
def emit(self, record): if record.levelno <= logging.ERROR: request = None exc_info = None for frame_info in getouterframes(currentframe()): frame = frame_info[0] if not request: request = frame.f_locals.get('request', None) if not request: view = frame.f_locals.get('self', None) request = getattr(view, 'request', None) if not exc_info: exc_info = frame.f_locals.get('exc_info', None) if not hasattr(exc_info, '__getitem__'): exc_info = None if request and exc_info: break if exc_info: record.exc_info = exc_info record.stack = \ iter_stack_frames(getinnerframes(exc_info[2])) if request: try: body_pos = request.stdin.tell() request.stdin.seek(0) body = request.stdin.read() request.stdin.seek(body_pos) http = dict(headers=request.environ, url=request.getURL(), method=request.method, host=request.environ.get('REMOTE_ADDR', ''), data=body) if 'HTTP_USER_AGENT' in http['headers']: if 'User-Agent' not in http['headers']: http['headers']['User-Agent'] = \ http['headers']['HTTP_USER_AGENT'] if 'QUERY_STRING' in http['headers']: http['query_string'] = http['headers']['QUERY_STRING'] setattr(record, 'sentry.interfaces.Http', http) user = request.get('AUTHENTICATED_USER', None) if user is not None: user_dict = dict( id=user.getId(), is_authenticated=user.has_role('Authenticated'), email=user.getProperty('email') or '') else: user_dict = {'is_authenticated': False} setattr(record, 'sentry.interfaces.User', user_dict) except (AttributeError, KeyError): logger.warning('Could not extract data from request', exc_info=True) return super(ZopeSentryHandler, self).emit(record)
def get_error_snapshot(depth=5): """Return a dict describing a given traceback (based on cgitb.text).""" etype, evalue, etb = sys.exc_info() if isinstance(etype, type): etype = etype.__name__ data = {} data["timestamp"] = datetime.datetime.utcnow().isoformat() data["python_version"] = sys.version platform_keys = [ "machine", "node", "platform", "processor", "python_branch", "python_build", "python_compiler", "python_implementation", "python_revision", "python_version", "python_version_tuple", "release", "system", "uname", "version", ] data["platform_info"] = {key: getattr(platform, key)() for key in platform_keys} data["os_environ"] = {key: str(value) for key, value in os.environ.items()} data["traceback"] = traceback.format_exc() data["exception_type"] = str(etype) data["exception_value"] = str(evalue) # Loopover the stack frames items = inspect.getinnerframes(etb, depth) del etb # Prevent circular references that would cause memory leaks data["stackframes"] = stackframes = [] for frame, file, lnum, func, lines, idx in items: file = file and os.path.abspath(file) or "?" args, varargs, varkw, locals = inspect.getargvalues(frame) # Basic frame information f = {"file": file, "func": func, "lnum": lnum} f["code"] = lines line_vars = cgitb.scanvars(lambda: linecache.getline(file, lnum), frame, locals) # Dump local variables (referenced in current line only) f["vars"] = { key: repr(value) for key, value in locals.items() if not key.startswith("__") } stackframes.append(f) return data
def user_frame(tb): if not inspect.istraceback(tb): raise ValueError('could not retrieve frame: argument not a traceback') for finfo in reversed(inspect.getinnerframes(tb)): module = inspect.getmodule(finfo.frame) if module is None: continue if not module.__name__.startswith('reframe'): return finfo return None
def wrapped_fn(): traceback = None try: return fn() except Exception as exc: (_, __, traceback) = sys.exc_info() frame = inspect.getinnerframes(traceback)[-1][0] frame_locals = frame.f_locals logger.exception("", exc_info=exc) pprint.pprint(frame_locals) finally: del locals()["traceback"]
def extract_full_exception_stack(err): tbk = sys.exc_info()[2] message = str(err) + '\nTraceback (most recent call last):' for item in reversed(inspect.getouterframes(tbk.tb_frame)[1:]): message += ' File "{1}", line {2}, in {3}\n'.format(*item) for line in item[4]: message += ' ' + line.lstrip() for item in inspect.getinnerframes(tbk): message += ' File "{1}", line {2}, in {3}\n'.format(*item) for line in item[4]: message += ' ' + line.lstrip() message += '%s: %s' % (err.__class__, err) return message
def get_records(tb, cache): """Get the traceback frrame history, excluding those originating from our own code included either at the beginning or at the end of the traceback. """ records = inspect.getinnerframes(tb, cache.context) records = list( dropwhile(lambda record: is_excluded_file(record.filename), records)) records.reverse() records = list( dropwhile(lambda record: is_excluded_file(record.filename), records)) records.reverse() return records
def testTracebackFrameLinkage(self): def a(): # raise an exception 1 // 0 def b(): return a() def c(): return b() def d(): try: c() except ZeroDivisionError: return sys.exc_info()[2] tb = d() # this way tb dosn't reference the current frame innerframes_orig = inspect.getinnerframes(tb) p = self.dumps(tb) tb2 = self.loads(p) # basics innerframes_orig = inspect.getinnerframes(tb) self.assertIs(type(tb), type(tb2)) self.assertIsNot(tb, tb2) innerframes = inspect.getinnerframes(tb2) # compare the content self.assertListEqual([i[1:] for i in innerframes_orig], [i[1:] for i in innerframes]) # check linkage all_outerframes_orig = inspect.getouterframes(innerframes_orig[-1][0]) all_outerframes = inspect.getouterframes(innerframes[-1][0]) l = len(innerframes_orig) # @IgnorePep8 self.assertGreater(len(all_outerframes_orig), l) self.assertGreaterEqual(len(all_outerframes), l) # compare the content self.assertListEqual([i[1:] for i in all_outerframes_orig[:l - 1]], [i[1:] for i in all_outerframes[:l - 1]])
def __exit__(self, exc_type, exc_val, exc_tb): if isinstance(exc_val, AssertionError): frame = inspect.currentframe().f_back frame_info = inspect.getinnerframes(exc_tb)[-1] desc = None if exc_val.args: if isinstance(exc_val.args[0], error): return desc = str(exc_val) exc_val.args = (error(desc=desc, frame=frame, frame_info=frame_info), ) self.errors.append(exc_val) return True
def format_ex(e): out_str = "" out_str += 'Exception thrown, %s: %s\n' % (type(e), str(e)) frames = inspect.getinnerframes(sys.exc_info()[2]) for frame_info in reversed(frames): f_locals = frame_info[0].f_locals if '__lgw_marker_local__' in f_locals: continue # log the frame information out_str += (' File "%s", line %i, in %s\n %s\n' % (frame_info[1], frame_info[2], frame_info[3], frame_info[4][0].lstrip())) # log every local variable of the frame for k, v in f_locals.items(): try: out_str += (' %s = %s\n' % (k, log_to_str(v))) except: pass return out_str
def generate_html(self, exc: Exception, limit: int = 7) -> str: traceback_obj = traceback.TracebackException.from_exception( exc, capture_locals=True ) frames = inspect.getinnerframes( traceback_obj.exc_traceback, limit # type: ignore ) center_lineno = int((limit - 1) / 2) exc_html = "".join( self.generate_frame_html(frame, center_lineno) for frame in reversed(frames) ) error = f"{traceback_obj.exc_type.__name__}: {traceback_obj}" return TEMPLATE.format(styles=STYLES, js=JS, error=error, exc_html=exc_html)
def __init__(self, exc_type, exc_value, exc_traceback, options): self.className = exc_type.__name__ self.message = "%s: %s" % (exc_type.__name__, exc_value) self.stackTrace = [] frames = None try: frames = inspect.getinnerframes(exc_traceback) if frames: for frame in frames: localVariables = None if 'transmitLocalVariables' in options and options[ 'transmitLocalVariables'] is True: localVariables = self._get_locals(frame[0]) self.stackTrace.append({ 'lineNumber': frame[2], 'className': frame[3], 'fileName': frame[1], 'methodName': frame[4][0] if frame[4] is not None else None, 'localVariables': localVariables }) if 'transmitGlobalVariables' in options and options[ 'transmitGlobalVariables'] is True and len(frames) > 0: self.globalVariables = frames[-1][0].f_globals finally: del frames self.data = "" try: jsonpickle.encode(self, unpicklable=False) except Exception as e: if self.globalVariables: self.globalVariables = None try: jsonpickle.encode(self, unpicklable=False) except Exception as e: for frame in self.stackTrace: if 'localVariables' in frame: frame['localVariables'] = None
def iter_tb_lines( e: Optional[Exception] = None, tb: Optional[Union[inspect.Traceback, TracebackType]] = None, num_skipped_frames: int = 0, max_value_str_len: int = 1000, max_exc_str_len: int = 10000, ellipsis_: str = '...', num_context_lines: int = 1, color_scheme: ColorScheme = ColorSchemes.none, __force_bug_mode: int = 0, # for tests only ) -> Iterator[str]: e_: Exception = e or sys.exc_info()[1] tb_: Union[inspect.Traceback, TracebackType] = tb or sys.exc_info()[2] c = color_scheme try: yield f'{c.c}Traceback with variables (most recent call last):{c.e}' for frame, filename, line_num, func_name, code_lines, func_line_num in \ inspect.getinnerframes(tb_, context=num_context_lines)[num_skipped_frames:]: yield f'{c.c} File "{c.f_}{filename}{c.c_}", line {c.ln_}{line_num}{c.c_}, in {c.fn_}{func_name}{c.e}' if code_lines: yield f'{c.c} {c.fs_}{"".join(code_lines).strip()}{c.e}' try: for var_name, var in frame.f_locals.items(): var_str = _to_cropped_str(var, max_value_str_len, max_exc_str_len, ellipsis_) var_lines = var_str.split('\n') yield f'{c.c} {c.n_}{var_name}{c.c_} = {c.v_}{var_lines[0] if var_lines else var_str}{c.e}' for line in var_lines[1:]: yield f'{c.c} {c.v_}{line}{c.e}' if __force_bug_mode == 1: raise ValueError('force_bug_mode') except: # noqa # indicates a bug in this lib yield ' <traceback-with-variables: exception while printing variables>' yield f' {traceback.format_exc()}' yield f'{c.ec}{e_.__class__.__module__}.{e_.__class__.__name__}:{c.et_} {e_}{c.e}' if __force_bug_mode == 2: raise ValueError('force_bug_mode') except: # noqa # indicates a bug in this lib yield ' <traceback-with-variables: exception while printing variables>' yield f'{traceback.format_exc()}'
def __init__(self): """ Create the debugger object from the most recent traceback. TESTS:: sage: a = sage0.eval("sage.interacts.debugger.test_function('n', 'm')") sage: sage0('sage.interacts.debugger.Debug()') <sage.interacts.debugger.Debug instance at 0x...> """ import inspect, sys, traceback try: self._stack = inspect.getinnerframes(sys.last_traceback) except AttributeError: raise RuntimeError, "no traceback has been produced; nothing to debug" self._curframe_index = len(self._stack) - 1
def getBacktraceDetailed(self, tracebackObject=None, frame=None, startframe=0, framecount=50): """ Get stackframe log is a very detailed log with filepaths, code locations & global vars, this output can become quite big """ import inspect if j.application.skipTraceback: return "" sep = "\n" + "-" * 90 + "\n" result = '' if tracebackObject is None: if frame is None: frame = inspect.currentframe() frames = inspect.getouterframes(frame, 16)[::-1] else: frames = inspect.getinnerframes(tracebackObject, 16) frames = frames[startframe:] for (frame, filename, lineno, fun, context, idx) in frames[-framecount:]: location = filename + "(line %d) (function %s)\n" % (lineno, fun) if location.find("EventHandler.py") == -1: result += " " + sep result += " " + location result += " " + "========== STACKFRAME==========\n" if context: l = 0 for line in context: prefix = " " if l == idx: prefix = "--> " l += 1 result += prefix + line result += " " + "============ LOCALS============\n" for (k, v) in sorted(frame.f_locals.items()): if self._filterLocals(k, v): try: result += " %.50s : %.1000s\n" % (str(k), str(v)) except: pass lines = result.split('\n')[:-1000] return '\n'.join(lines)
def write_post_mortem( self, etype, value, tb ): 'write exception nfo to html log' _fmt = lambda obj: '=' + ''.join( s.strip() for s in repr(obj).split('\n') ) self._print('<div class="post-mortem">') self._print( 'EXHAUSTIVE STACK TRACE' ) self._print() for frame, filename, lineno, function, code_context, index in inspect.getinnerframes( tb ): self._print( 'File "{}", line {}, in {}'.format( filename, lineno, function ) ) self._print( html.escape( textwrap.fill( inspect.formatargvalues(*inspect.getargvalues(frame),formatvalue=_fmt), initial_indent=' ', subsequent_indent=' ', width=80 ) ) ) if code_context: self._print() for line in code_context: self._print( html.escape( textwrap.fill( line.strip(), initial_indent='>>> ', subsequent_indent=' ', width=80 ) ) ) self._print() self._print('</div>') self._flush()
def generate_html(self, exc: Exception, limit: int = 7) -> str: traceback_obj = traceback.TracebackException.from_exception( exc, capture_locals=True) exc_html = "" is_collapsed = False exc_traceback = exc.__traceback__ if exc_traceback is not None: frames = inspect.getinnerframes(exc_traceback, limit) for frame in reversed(frames): exc_html += self.generate_frame_html(frame, is_collapsed) is_collapsed = True # escape error class and text error = f"{html.escape(traceback_obj.exc_type.__name__)}: {html.escape(str(traceback_obj))}" return TEMPLATE.format(styles=STYLES, error=error, exc_html=exc_html)
def noch_parse_exception(error_object, *args): merc.GDF = False wrap_call = inspect.getinnerframes(sys.exc_info()[2]) logger.debug("Exception: %s %s" % (type(error_object), str(error_object))) for call_info in reversed(wrap_call): local_calls = call_info[0].f_locals if '_logged__tracer_var_' in local_calls: continue tracestring = "Frame Trace: \nFile: %s \nLine: %d \n ", call_info[ 1], call_info[2] tracestring += "Function: %s \nCode: %s ", call_info[3], call_info[4][ 0].lstrip() logger.debug(tracestring) logger.debug("Local Env Variables: ") for k, v in local_calls.items(): levtrace = value_to_str(v) logger.debug("%s : %s", k, levtrace)
def initialize(self): self.is_post_mortem = False self.code = "" self.breakpoints = [] self.is_post_mortem = self.pixieapp_entity is None or self.pixieapp_entity["code"] is None if self.is_post_mortem: if not hasattr(sys, "last_traceback") or sys.last_traceback is None: raise NoTraceback() if self.options.get("debug_route", "false" ) == "true": stack = [tb.function if PY3 else tb[3] for tb in inspect.getinnerframes(sys.last_traceback)] method_name = stack[-1] for method in reversed(stack): code = self.parent_pixieapp.exceptions.get(method, None) if code: method_name = method break self.pixieapp_entity = { "breakpoints": ["{}.{}".format(self.parent_pixieapp.__pixieapp_class_name__, method_name)], "code": code or "" } self.debug("Invoking PixieDebugger for route with {}".format(self.pixieapp_entity)) self.is_post_mortem = False if not self.is_post_mortem: self.code = self.renderTemplateString(""" def pixie_run(): import pdb pdb.set_trace() {{this.pixieapp_entity["code"]|indent(4, indentfirst=True)}} pixie_run() """.strip()) bps_lines = set() bps_fns = set() for breakpoint in self.pixieapp_entity["breakpoints"] or []: try: bps_lines.add( int(breakpoint)) except ValueError: matches = get_matches_lineno(self.code, breakpoint) if len(matches) == 0: bps_fns.add(breakpoint) else: for match in matches: bps_lines.add(match) self.breakpoints = list(sorted(bps_lines)) + list(sorted(bps_fns)) else: self.code="""
def ptb(einfo, original, path, context, locals, builtins): """ Return pretty traceback for given exception. :param einfo: tuple with exception info. :param context: int, number of lines to be displayed. :return: string, pretty traceback. """ et, ev, tb = einfo frame_records = inspect.getinnerframes(tb, context) pretty_tb = 'Pretty Traceback: \n\n' for frame_record in frame_records: fname, call, code, objects, frame_vars = frame_parser(frame_record) if path: if path not in fname: continue fname = '{:<10} {}\n'.format('File:', fname) call = '{:<10} {}\n'.format('Call:', call) context = '{:<10}\n{}\n'.format('Context:', code) objects = format_objects(objects) objects = ', '.join(objects) objects = '{:<10} {}\n'.format('Objects:', objects) local_vars, local_builtins = format_locals(frame_vars) pretty_tb = pretty_tb + fname + call + context + objects if locals: pretty_tb = pretty_tb + local_vars if builtins: pretty_tb = pretty_tb + local_builtins pretty_tb = pretty_tb + '\n' if original: original_tb = '{} {}\n\n'.format( 'Original Traceback: \n', ''.join(traceback.format_exception(*einfo))) pretty_tb = original_tb + pretty_tb pretty_tb = '{}{}: {}'.format(pretty_tb, str(et)[8:-2], str(ev)) return pretty_tb
def user_frame(exc_type, exc_value, tb): '''Return a user frame from the exception's traceback. As user frame is considered the first frame that is outside from :mod:`reframe` module. :returns: A frame object or :class:`None` if no user frame was found. ''' if not inspect.istraceback(tb): return None for finfo in reversed(inspect.getinnerframes(tb)): relpath = os.path.relpath(finfo.filename, sys.path[0]) if relpath.split(os.sep)[0] != 'reframe': return finfo return None
def print_full_stack(tb=None): """ Only good way to print stack trace yourself. http://blog.dscpl.com.au/2015/03/generating-full-stack-traces-for.html """ if tb is None: tb = sys.exc_info()[2] print('Traceback (most recent call last):') if (not (tb == None)): for item in reversed(inspect.getouterframes(tb.tb_frame)[1:]): print(' File "{1}", line {2}, in {3}\n'.format(*item), ) for line in item[4]: print(' ' + line.lstrip(), ) for item in inspect.getinnerframes(tb): print(' File "{1}", line {2}, in {3}\n'.format(*item), ) for line in item[4]: print(' ' + line.lstrip(), )
def get_error_snapshot(depth=5): """Return a dict describing a given traceback (based on cgitb.text).""" etype, evalue, etb = sys.exc_info() if isinstance(etype, type): etype = etype.__name__ data = {} data['timestamp'] = datetime.datetime.utcnow().isoformat() data['python_version'] = sys.version platform_keys = [ 'machine', 'node', 'platform', 'processor', 'python_branch', 'python_build', 'python_compiler', 'python_implementation', 'python_revision', 'python_version', 'python_version_tuple', 'release', 'system', 'uname', 'version' ] data['platform_info'] = { key: getattr(platform, key)() for key in platform_keys } data['os_environ'] = {key: str(value) for key, value in os.environ.items()} data['traceback'] = traceback.format_exc() data['exception_type'] = str(etype) data['exception_value'] = str(evalue) # Loopover the stack frames items = inspect.getinnerframes(etb, depth) del etb # Prevent circular references that would cause memory leaks data['stackframes'] = stackframes = [] for frame, file, lnum, func, lines, idx in items: file = file and os.path.abspath(file) or '?' args, varargs, varkw, locals = inspect.getargvalues(frame) # Basic frame information f = {'file': file, 'func': func, 'lnum': lnum} f['code'] = lines line_vars = cgitb.scanvars(lambda: linecache.getline(file, lnum), frame, locals) # Dump local variables (referenced in current line only) f['vars'] = { key: repr(value) for key, value in locals.items() if not key.startswith('__') } stackframes.append(f) return data
def format_pretty_traceback(tb): parts = [] for frame in inspect.getinnerframes(tb, 5): line_info = '{} {}:{}\n'.format(frame[3], frame[1], frame[2]) parts.append(line_info) parts.append('-' * (len(line_info) - 1)) parts.append('\n') if frame[0].f_locals: parts.append(data_printer.printout(frame[0].f_locals)) leading_space = min( [len(l) - len(l.lstrip()) for l in frame[4] if l.lstrip()]) parts.append('\n') for i, line in enumerate(frame[4]): if line.lstrip(): line = line[leading_space:] prefix = '* ' if i == frame[5] else ' ' parts.append(prefix + line) parts.append('\n') return ''.join(parts)