我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.last_value()。
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 format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the list. """ return list(TracebackException(etype, value, None).format_exception_only()) # -- not offical API but folk probably use these two functions.
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 test_base_exception(self): # Test that exceptions derived from BaseException are formatted right e = KeyboardInterrupt() lst = traceback.format_exception_only(e.__class__, e) self.assertEqual(lst, ['KeyboardInterrupt\n']) # String exceptions are deprecated, but legal. The quirky form with # separate "type" and "value" tends to break things, because # not isinstance(value, type) # and a string cannot be the first argument to issubclass. # # Note that sys.last_type and sys.last_value do not get set if an # exception is caught, so we sort of cheat and just emulate them. # # test_string_exception1 is equivalent to # # >>> raise "String Exception" # # test_string_exception2 is equivalent to # # >>> raise "String Exception", "String Value" #
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 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 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 format_exception_only(etype, value): """Format the exception part of a traceback. The arguments are the exception type and value such as given by sys.last_type and sys.last_value. The return value is a list of strings, each ending in a newline. Normally, the list contains a single string; however, for SyntaxError exceptions, it contains several lines that (when printed) display detailed information about where the syntax error occurred. The message indicating which exception occurred is always the last string in the list. """ return list(_format_exception_only_iter(etype, value))
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_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 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 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)
def showsyntaxerror(self, filename=None): 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, dummy_line) = value.args except ValueError: # Not the format we expect; leave it alone pass else: # Stuff in the right filename and line print(self.buffer, lineno) line = dummy_line value = SyntaxError(msg, (filename, lineno, offset, line)) sys.last_value = value if 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.write sys.excepthook(type, value, tb)
def _get_exc_info(self, exc_tuple=None): """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. Ensures sys.last_type,value,traceback hold the exc_info we found, from whichever source. raises ValueError if none of these contain any information """ if exc_tuple is None: etype, value, tb = sys.exc_info() else: etype, value, tb = exc_tuple if etype is None: if hasattr(sys, 'last_type'): etype, value, tb = sys.last_type, sys.last_value, \ sys.last_traceback if etype is None: raise ValueError("No exception to find") # Now store the exception info in sys.last_type etc. # WARNING: these variables are somewhat deprecated and not # necessarily safe to use in a threaded environment, but tools # like pdb depend on their existence, so let's set them. If we # find problems in the field, we'll need to revisit their use. sys.last_type = etype sys.last_value = value sys.last_traceback = tb return etype, value, tb
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") if file is None: file = sys.stderr print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file, chain)
def report_callback_exception(self, exc, val, tb): """Internal function. It reports exception on sys.stderr.""" import traceback, sys sys.stderr.write("Exception in Tkinter callback\n") sys.last_type = exc sys.last_value = val sys.last_traceback = tb traceback.print_exception(exc, val, tb)
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.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 lines = traceback.format_exception_only(type, value) self.write(''.join(lines))
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. """ sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() sys.last_traceback = last_tb try: lines = [] for value, tb in traceback._iter_chain(*ei[1:]): if isinstance(value, str): lines.append(value) lines.append('\n') continue if tb: tblist = traceback.extract_tb(tb) if tb is last_tb: # The last traceback includes the frame we # exec'd in del tblist[:1] tblines = traceback.format_list(tblist) if tblines: lines.append("Traceback (most recent call last):\n") lines.extend(tblines) lines.extend(traceback.format_exception_only(type(value), value)) finally: tblist = last_tb = ei = None self.write(''.join(lines))
def stackviewer(self, flist_oid=None): if self.usr_exc_info: typ, val, tb = self.usr_exc_info else: return None flist = None if flist_oid is not None: flist = self.rpchandler.get_remote_proxy(flist_oid) while tb and tb.tb_frame.f_globals["__name__"] in ["rpc", "run"]: tb = tb.tb_next sys.last_type = typ sys.last_value = val item = StackViewer.StackTreeItem(flist, tb) return RemoteObjectBrowser.remote_object_tree_item(item)
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, sys print >>sys.stderr, "Exception in Tkinter callback" sys.last_type = exc sys.last_value = val sys.last_traceback = tb traceback.print_exception(exc, val, tb)