我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.last_traceback()。
def verifyStderr(self, method, successRe) : """ Call method() while capturing sys.stderr output internally and call self.fail() if successRe.search() does not match the stderr output. This is used to test for uncatchable exceptions. """ stdErr = sys.stderr sys.stderr = StringIO() try: method() finally: temp = sys.stderr sys.stderr = stdErr errorOut = temp.getvalue() if not successRe.search(errorOut) : self.fail("unexpected stderr output:\n"+errorOut) if sys.version_info < (3, 0) : # XXX: How to do this in Py3k ??? sys.exc_traceback = sys.last_traceback = None
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 = type sys.last_value = value sys.last_traceback = tb tblist = traceback.extract_tb(tb) del tblist[:1] list = traceback.format_list(tblist) if list: list.insert(0, "Traceback (most recent call last):\n") list[len(list):] = traceback.format_exception_only(type, value) finally: tblist = tb = None map(self.write, list)
def debugger(self,force=False): """Call the pdb debugger. Keywords: - force(False): by default, this routine checks the instance call_pdb flag and does not actually invoke the debugger if the flag is false. The 'force' option forces the debugger to activate even if the flag is false. """ if not (force or self.call_pdb): return if not hasattr(sys,'last_traceback'): error('No traceback has been produced, nothing to debug.') return self.InteractiveTB.debugger(force=True) #------------------------------------------------------------------------- # Things related to IPython's various namespaces #-------------------------------------------------------------------------
def print_exception(): import linecache linecache.checkcache() flush_stdout() efile = sys.stderr typ, val, tb = excinfo = sys.exc_info() sys.last_type, sys.last_value, sys.last_traceback = excinfo tbe = traceback.extract_tb(tb) print('Traceback (most recent call last):', file=efile) exclude = ("run.py", "rpc.py", "threading.py", "queue.py", "RemoteDebugger.py", "bdb.py") cleanup_traceback(tbe, exclude) traceback.print_list(tbe, file=efile) lines = traceback.format_exception_only(typ, val) for line in lines: print(line, end='', file=efile)
def _stack_viewer(parent): # htest # root = tk.Tk() root.title("Test StackViewer") width, height, x, y = list(map(int, re.split('[x+]', parent.geometry()))) root.geometry("+%d+%d"%(x, y + 150)) flist = PyShellFileList(root) try: # to obtain a traceback object intentional_name_error except NameError: exc_type, exc_value, exc_tb = sys.exc_info() # inject stack trace to sys sys.last_type = exc_type sys.last_value = exc_value sys.last_traceback = exc_tb StackBrowser(root, flist=flist, top=root, tb=exc_tb) # restore sys to original state del sys.last_type del sys.last_value del sys.last_traceback
def step_impl(context): """ :type context behave.runner.Context """ _json_data = json_load_file(os.path.join(script_location, "../data/bad_json.json")) try: context.schema_tools.apply(_json_data) except Exception as e: if str(e)[:32] == "'canRead' is a required property": ok_(True) else: if hasattr(sys, "last_traceback"): _traceback = traceback.print_tb(sys.last_traceback) else: _traceback = "Not available" ok_(False, "Error: " + str(e) + "\nTraceback:" + _traceback)
def showsyntaxerror(self, filename=None): """Display the syntax error that just occurred.""" #Override for avoid using sys.excepthook PY-12600 type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value list = traceback.format_exception_only(type, value) sys.stderr.write(''.join(list))
def showtraceback(self): """Display the exception that just occurred.""" #Override for avoid using sys.excepthook PY-12600 try: type, value, tb = sys.exc_info() sys.last_type = type sys.last_value = value sys.last_traceback = tb tblist = 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 = None sys.stderr.write(''.join(lines))
def post_mortem(t=None): if t is None: t = sys.exc_info()[2] # Will be valid if we are called from an except handler. if t is None: try: t = sys.last_traceback except AttributeError: print "No traceback can be found from which to perform post-mortem debugging!" print "No debugging can continue" return p = _GetCurrentDebugger() if p.frameShutdown: return # App closing # No idea why I need to settrace to None - it should have been reset by now? sys.settrace(None) p.reset() while t.tb_next != None: t = t.tb_next p.bAtPostMortem = 1 p.prep_run(None) try: p.interaction(t.tb_frame, t) finally: t = None p.bAtPostMortem = 0 p.done_run()
def post_mortem(t=None): if t is None: t = sys.exc_info()[2] # Will be valid if we are called from an except handler. if t is None: try: t = sys.last_traceback except AttributeError: print("No traceback can be found from which to perform post-mortem debugging!") print("No debugging can continue") return p = _GetCurrentDebugger() if p.frameShutdown: return # App closing # No idea why I need to settrace to None - it should have been reset by now? sys.settrace(None) p.reset() while t.tb_next != None: t = t.tb_next p.bAtPostMortem = 1 p.prep_run(None) try: p.interaction(t.tb_frame, t) finally: t = None p.bAtPostMortem = 0 p.done_run()
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 instead of what was there before (because Python's parser always uses "<string>" when reading from a string). """ etype, value, last_traceback = self._get_exc_info() if filename and issubclass(etype, SyntaxError): try: value.filename = filename except: # Not the format we expect; leave it alone pass stb = self.SyntaxTB.structured_traceback(etype, value, []) self._showtraceback(etype, value, stb) # This is overridden in TerminalInteractiveShell to show a message about # the %paste magic.
def _stack_viewer(parent): root = tk.Tk() root.title("Test StackViewer") width, height, x, y = list(map(int, re.split('[x+]', parent.geometry()))) root.geometry("+%d+%d"%(x, y + 150)) flist = PyShellFileList(root) try: # to obtain a traceback object intentional_name_error except NameError: exc_type, exc_value, exc_tb = sys.exc_info() # inject stack trace to sys sys.last_type = exc_type sys.last_value = exc_value sys.last_traceback = exc_tb StackBrowser(root, flist=flist, top=root, tb=exc_tb) # restore sys to original state del sys.last_type del sys.last_value del sys.last_traceback
def print_exception(): import linecache linecache.checkcache() flush_stdout() efile = sys.stderr typ, val, tb = excinfo = sys.exc_info() sys.last_type, sys.last_value, sys.last_traceback = excinfo tbe = traceback.extract_tb(tb) print>>efile, '\nTraceback (most recent call last):' exclude = ("run.py", "rpc.py", "threading.py", "Queue.py", "RemoteDebugger.py", "bdb.py") cleanup_traceback(tbe, exclude) traceback.print_list(tbe, file=efile) lines = traceback.format_exception_only(typ, val) for line in lines: print>>efile, line,
def test_dis_traceback(self): self.skipTest('Fix up ability to disassemble straceback') return try: del sys.last_traceback except AttributeError: pass try: 1/0 except Exception as e: tb = e.__traceback__ sys.last_traceback = tb tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti) self.do_disassembly_test(None, tb_dis)
def test_dis_traceback(self): self.skipTest('Fix up ability to disassemble straceback') return try: del sys.last_traceback except AttributeError: pass try: 1/0 except Exception as e: tb = e.__traceback__ sys.last_traceback = tb tb_dis = self.get_disassemble_as_string(tb.tb_frame.f_code, tb.tb_lasti) self.dis_disassembly34(None, tb_dis)
def test_store_except_info_on_eror(): """ Test that upon test failure, the exception info is stored on sys.last_traceback and friends. """ # Simulate item that raises a specific exception class ItemThatRaises: def runtest(self): raise IndexError('TEST') try: runner.pytest_runtest_call(ItemThatRaises()) except IndexError: pass # Check that exception info is stored on sys assert sys.last_type is IndexError assert sys.last_value.args[0] == 'TEST' assert sys.last_traceback
def pm(): post_mortem(sys.last_traceback) # Main program for testing
def print_last(limit=None, file=None): """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") if file is None: file = sys.stderr print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)
def distb(tb=None): """Disassemble a traceback (default: last traceback).""" if tb is None: try: tb = sys.last_traceback except AttributeError: raise RuntimeError, "no last traceback to disassemble" while tb.tb_next: tb = tb.tb_next disassemble(tb.tb_frame.f_code, tb.tb_lasti)
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 instead of 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, sys.last_traceback = sys.exc_info() sys.last_type = type sys.last_value = value if filename and type is SyntaxError: # Work hard to stuff the correct filename in the exception try: msg, (dummy_filename, lineno, offset, line) = value except: # Not the format we expect; leave it alone pass else: # Stuff in the right filename value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value list = traceback.format_exception_only(type, value) map(self.write, list)
def __call__(self, *args): ## Start by extending recursion depth just a bit. ## If the error we are catching is due to recursion, we don't want to generate another one here. recursionLimit = sys.getrecursionlimit() try: sys.setrecursionlimit(recursionLimit+100) ## call original exception handler first (prints exception) global original_excepthook, callbacks, clear_tracebacks try: print("===== %s =====" % str(time.strftime("%Y.%m.%d %H:%m:%S", time.localtime(time.time())))) except Exception: sys.stderr.write("Warning: stdout is broken! Falling back to stderr.\n") sys.stdout = sys.stderr ret = original_excepthook(*args) for cb in callbacks: try: cb(*args) except Exception: print(" --------------------------------------------------------------") print(" Error occurred during exception callback %s" % str(cb)) print(" --------------------------------------------------------------") traceback.print_exception(*sys.exc_info()) ## Clear long-term storage of last traceback to prevent memory-hogging. ## (If an exception occurs while a lot of data is present on the stack, ## such as when loading large files, the data would ordinarily be kept ## until the next exception occurs. We would rather release this memory ## as soon as possible.) if clear_tracebacks is True: sys.last_traceback = None finally: sys.setrecursionlimit(recursionLimit)
def pytest_runtest_call(item): try: item.runtest() except Exception: # Store trace info to allow postmortem debugging type, value, tb = sys.exc_info() tb = tb.tb_next # Skip *this* frame sys.last_type = type sys.last_value = value sys.last_traceback = tb del tb # Get rid of it in this namespace raise
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 report_callback_exception(self, exc, val, tb): """Report callback exception on sys.stderr. Applications may want to override this internal function, and should when sys.stderr is None.""" import traceback print("Exception in Tkinter callback", file=sys.stderr) sys.last_type = exc sys.last_value = val sys.last_traceback = tb traceback.print_exception(exc, val, tb)