我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用traceback.format_exception_only()。
def format_exception(bfn, ex): import traceback, linecache exinfo = traceback.format_exception_only(ex.__class__, ex) if ex.__class__ == SyntaxError: exinfo = exinfo[1:] lineno = ex.lineno content = '' sys.stderr.write('Error while processing %s:%s\n\t%s\n' % (os.path.abspath(bfn), lineno, content.strip())) else: exec_line = None exloc = traceback.extract_tb(sys.exc_info()[2]) for idx, entry in enumerate(exloc): if entry[3] is None: exec_line = idx if exec_line is not None: exloc = [(bfn, exloc[exec_line][1], '', linecache.getline(bfn, exloc[exec_line][1]))] + exloc[exec_line:] sys.stderr.write('Error while processing %s\n' % os.path.abspath(bfn)) sys.stderr.write(str.join('', traceback.format_list(exloc))) sys.stderr.write(str.join('', exinfo)) sys.exit(1)
def print_exception(type=None, value=None, tb=None, limit=None): if type is None: type, value, tb = sys.exc_info() import traceback print print "<H3>Traceback (most recent call last):</H3>" list = traceback.format_tb(tb, limit) + \ traceback.format_exception_only(type, value) print "<PRE>%s<B>%s</B></PRE>" % ( escape("".join(list[:-1])), escape(list[-1]), ) del tb
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 print_exception(exc_type, exc_value, exc_tb): # remove debugger frames from the top and bottom of the traceback tb = traceback.extract_tb(exc_tb) for i in [0, -1]: while tb: frame_file = path.normcase(tb[i][0]) if not any(is_same_py_file(frame_file, f) for f in DONT_DEBUG): break del tb[i] # print the traceback if tb: print('Traceback (most recent call last):') for out in traceback.format_list(tb): sys.stderr.write(out) # print the exception for out in traceback.format_exception_only(exc_type, exc_value): sys.stdout.write(out)
def user_exception(self, frame, info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" if self._wait_for_mainpyfile or self._wait_for_breakpoint: return extype, exvalue, trace = info # pre-process stack trace as it isn't pickeable (cannot be sent pure) msg = ''.join(traceback.format_exception(extype, exvalue, trace)) # in python3.5, convert FrameSummary to tuples (py2.7+ compatibility) tb = [tuple(fs) for fs in traceback.extract_tb(trace)] title = traceback.format_exception_only(extype, exvalue)[0] # send an Exception notification msg = {'method': 'exception', 'args': (title, extype.__name__, repr(exvalue), tb, msg), 'id': None} self.pipe.send(msg) self.interaction(frame)
def user_exception(self, frame, info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" if self._wait_for_mainpyfile or self._wait_for_breakpoint: return extype, exvalue, trace = info # pre-process stack trace as it isn't pickeable (cannot be sent pure) msg = ''.join(traceback.format_exception(extype, exvalue, trace)) trace = traceback.extract_tb(trace) title = traceback.format_exception_only(extype, exvalue)[0] # send an Exception notification msg = {'method': 'exception', 'args': (title, extype.__name__, exvalue, trace, msg), 'id': None} self.pipe.send(msg) self.interaction(frame, info)
def log_traceback_from_info(exception_type, value, tb, dst=sys.stderr, skip=0): """Log a given exception nicely to 'dst', showing a traceback. dst -- writeable file-like object skip -- number of traceback entries to omit from the top of the list """ for line in traceback.format_exception_only(exception_type, value): dst.write(line) if (not isinstance(exception_type, str) and issubclass(exception_type, SyntaxError)): return print >>dst, 'traceback (most recent call last):' text = None for filename, lineno, fnname, text in traceback.extract_tb(tb)[skip:]: if fnname == "?": fn_s = "<global scope>" else: fn_s = "(%s)" % fnname print >>dst, " %s:%s %s" % (filename, lineno, fn_s) if text is not None: print >>dst, "failing line:" print >>dst, text
def default(self, line): if line[:1] == '!': line = line[1:] locals = self.curframe_locals globals = self.curframe.f_globals try: code = compile(line + '\n', '<stdin>', 'single') save_stdout = sys.stdout save_stdin = sys.stdin save_displayhook = sys.displayhook try: sys.stdin = self.stdin sys.stdout = self.stdout sys.displayhook = self.displayhook exec(code, globals, locals) finally: sys.stdout = save_stdout sys.stdin = save_stdin sys.displayhook = save_displayhook except: exc_info = sys.exc_info()[:2] self.error(traceback.format_exception_only(*exc_info)[-1].strip())
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 instance(cls, statement, params, orig, dbapi_base_err, connection_invalidated=False): # Don't ever wrap these, just return them directly as if # DBAPIError didn't exist. if isinstance(orig, (KeyboardInterrupt, SystemExit, DontWrapMixin)): return orig if orig is not None: # not a DBAPI error, statement is present. # raise a StatementError if not isinstance(orig, dbapi_base_err) and statement: msg = traceback.format_exception_only( orig.__class__, orig)[-1].strip() return StatementError( "%s (original cause: %s)" % (str(orig), msg), statement, params, orig ) name, glob = orig.__class__.__name__, globals() if name in glob and issubclass(glob[name], DBAPIError): cls = glob[name] return cls(statement, params, orig, connection_invalidated)
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 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 process_ifconfig_nodes(app, doctree, docname): ns = dict((k, app.config[k]) for k in app.config.values) ns.update(app.config.__dict__.copy()) ns['builder'] = app.builder.name for node in doctree.traverse(ifconfig): try: res = eval(node['expr'], ns) except Exception as err: # handle exceptions in a clean fashion from traceback import format_exception_only msg = ''.join(format_exception_only(err.__class__, err)) newnode = doctree.reporter.error('Exception occured in ' 'ifconfig expression: \n%s' % msg, base_node=node) node.replace_self(newnode) else: if not res: node.replace_self([]) else: node.replace_self(node.children)
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_exc(limit=None, exception=None, tb_list=None): """ This is like print_exc(limit) but returns a string instead of printing to a file. """ result = ["Traceback (most recent call last):\n"] if exception is None: exception = get_context_with_traceback(get_async_context()).exception if tb_list is None: tb_list = extract_tb(limit) if tb_list: result.extend(traceback.format_list(tb_list)) result.extend(traceback.format_exception_only(exception.__class__, exception)) return result else: return None
def format_exc(self, limit=None): """ This is like exception.print_exc(limit) but returns a string instead of printing to a file. """ result = ["Traceback (most recent call last):\n"] tb_list = self._traceback if limit is not None: tb_list = tb_list[-limit:] result.extend(traceback.format_list(tb_list)) if self.cause is not None: result.extend(traceback.format_exception_only(self.cause.__class__, self.cause)) return result else: return result
def user_exception(self, frame, exc_info): """This function is called if an exception occurs, but only if we are to stop at or just below this level.""" if self._wait_for_mainpyfile: return exc_type, exc_value, exc_traceback = exc_info frame.f_locals['__exception__'] = exc_type, exc_value # An 'Internal StopIteration' exception is an exception debug event # issued by the interpreter when handling a subgenerator run with # 'yield from' or a generator controled by a for loop. No exception has # actually occurred in this case. The debugger uses this debug event to # stop when the debuggee is returning from such generators. prefix = 'Internal ' if (not exc_traceback and exc_type is StopIteration) else '' self.message('%s%s' % (prefix, traceback.format_exception_only(exc_type, exc_value)[-1].strip())) self.interaction(frame, exc_traceback) # General interaction function
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 __init__(self, exc_type, exc_value, file, msg=''): exc_type_name = exc_type.__name__ if exc_type is SyntaxError: tbtext = ''.join(traceback.format_exception_only(exc_type, exc_value)) errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file) else: errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value) Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file) self.exc_type_name = exc_type_name self.exc_value = exc_value self.file = file self.msg = msg or errmsg
def exception(self, message=None): "Log an exception as an error and debug if we're doing that." extype, ex, tb = sys.exc_info() message = "Exception: %s%s%s" % ( message + ': ' if message is not None else '', ''.join(traceback.format_exception_only(extype, ex)), ''.join(traceback.format_exception(extype, ex, tb)).strip() ) if self.forced_debug: self.debug(message) else: self.error(message) # Forced setting of debug level
def exceptionHandler(self, excType, exc, tb): if self.ui.catchNextExceptionBtn.isChecked(): self.ui.catchNextExceptionBtn.setChecked(False) elif not self.ui.catchAllExceptionsBtn.isChecked(): return self.ui.clearExceptionBtn.setEnabled(True) self.currentTraceback = tb excMessage = ''.join(traceback.format_exception_only(excType, exc)) self.ui.exceptionInfoLabel.setText(excMessage) self.ui.exceptionStackList.clear() for index, line in enumerate(traceback.extract_tb(tb)): self.ui.exceptionStackList.addItem('File "%s", line %s, in %s()\n %s' % line)
def exception(self): """String representation of the exception.""" buf = traceback.format_exception_only(self.exc_type, self.exc_value) rv = ''.join(buf).strip() return rv.decode('utf-8', 'replace') if PY2 else rv
def fallback_repr(self): try: info = ''.join(format_exception_only(*sys.exc_info()[:2])) except Exception: # pragma: no cover info = '?' if PY2: info = info.decode('utf-8', 'ignore') return u'<span class="brokenrepr"><broken repr (%s)>' \ u'</span>' % escape(info.strip())
def test(): "Run a simple demo that shows evaluator's capability." from sys import exc_info, stderr from traceback import format_exception_only local = {} while True: try: evaluate(input('>>> '), local) except EOFError: break except: stderr.write(format_exception_only(*exc_info()[:2])[-1])
def format_exception(self): """ Return the same data as from traceback.format_exception. """ import traceback frames = self.get_traceback_frames() tb = [(f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames] list = ['Traceback (most recent call last):\n'] list += traceback.format_list(tb) list += traceback.format_exception_only(self.exc_type, self.exc_value) return list
def exconly(self, tryshort=False): """ return the exception as a string when 'tryshort' resolves to True, and the exception is a py.code._AssertionError, only the actual exception part of the exception representation is returned (so 'AssertionError: ' is removed from the beginning) """ lines = format_exception_only(self.type, self.value) text = ''.join(lines) text = text.rstrip() if tryshort: if text.startswith(self._striptext): text = text[len(self._striptext):] return text
def codeInput(self, text): methodName = 'do' if text[0] == '/': split = string.split(text[1:],' ',1) statement = split[0] if len(split) == 2: remainder = split[1] if statement in ('browse', 'explore'): methodName = 'explore' text = remainder elif statement == 'watch': methodName = 'watch' text = remainder elif statement == 'self_rebuild': rebuild.rebuild(explorer) if _GNOME_POWER: rebuild.rebuild(spelunk_gnome) rebuild.rebuild(sys.modules[__name__]) return try: self.perspective.callRemote(methodName, text) except pb.ProtocolError: # ASSUMPTION: pb.ProtocolError means we lost our connection. (eType, eVal, tb) = sys.exc_info() del tb s = string.join(traceback.format_exception_only(eType, eVal), '') self.connectionLost(s) except: traceback.print_exc() gtk.mainquit()
def _failureOldStyle(fail): """Pre-Failure manhole representation of exceptions. For compatibility with manhole clients without the \"Failure\" capability. A dictionary with two members: - \'traceback\' -- traceback.extract_tb output; a list of tuples (filename, line number, function name, text) suitable for feeding to traceback.format_list. - \'exception\' -- a list of one or more strings, each ending in a newline. (traceback.format_exception_only output) """ import linecache tb = [] for f in fail.frames: # (filename, line number, function name, text) tb.append((f[1], f[2], f[0], linecache.getline(f[1], f[2]))) return { 'traceback': tb, 'exception': traceback.format_exception_only(fail.type, fail.value) } # Capabilities clients are likely to have before they knew how to answer a # "listCapabilities" query.
def istrue(self): try: return self._istrue() except Exception: self.exc = sys.exc_info() if isinstance(self.exc[1], SyntaxError): msg = [" " * (self.exc[1].offset + 4) + "^",] msg.append("SyntaxError: invalid syntax") else: msg = traceback.format_exception_only(*self.exc[:2]) pytest.fail("Error evaluating %r expression\n" " %s\n" "%s" %(self.name, self.expr, "\n".join(msg)), pytrace=False)