我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.exc_traceback()。
def open_file(self, url): path = urllib.url2pathname(urllib.unquote(url)) if os.path.isdir(path): if path[-1] != os.sep: url = url + '/' indexpath = os.path.join(path, "index.html") if os.path.exists(indexpath): return self.open_file(url + "index.html") try: names = os.listdir(path) except os.error, msg: raise IOError, msg, sys.exc_traceback names.sort() s = MyStringIO("file:"+url, {'content-type': 'text/html'}) s.write('<BASE HREF="file:%s">\n' % urllib.quote(os.path.join(path, ""))) for name in names: q = urllib.quote(name) s.write('<A HREF="%s">%s</A>\n' % (q, q)) s.seek(0) return s return urllib.FancyURLopener.open_file(self, url)
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 __init__(self, path = None): self.version = 1 self.fragments = [] self.path = path if path is not None and os.path.exists(path): currentresref = Res.CurResFile() resref = Res.FSpOpenResFile(path, 1) Res.UseResFile(resref) try: try: data = Res.Get1Resource('cfrg', 0).data except Res.Error: raise Res.Error, "no 'cfrg' resource found", sys.exc_traceback finally: Res.CloseResFile(resref) Res.UseResFile(currentresref) self.parse(data) if self.version != 1: raise error, "unknown 'cfrg' resource format"
def traceback_get_exception(num = -1): # build error message exception_string = ''.join(traceback.format_exception_only(sys.exc_type, hasattr(sys, 'exc_value') and sys.exc_value or 'Unknown')) # extract error location from traceback if hasattr(sys, 'exc_traceback'): (filename, line_number, function_name, text) = traceback.extract_tb(sys.exc_traceback)[num] else: (filename, line_number, function_name, text) = ('-', '-', '-', '-') error = { 'message': exception_string, 'location': { 'filename': filename, 'line_number': line_number, 'function_name': function_name, 'text': text, } } return error
def txn_proc(self, proc, txn): # can be used to txn protect a method automatically if not txn: if self.dbenv: autotxn = self.dbenv.txn_begin() try: retval = proc(autotxn) except db.DBError, e: autotxn.abort() raise e except Exception, e: autotxn.abort() e.args += tuple(traceback.format_tb(sys.exc_traceback)) raise e autotxn.commit() else: # execute without transactions retval = proc(None) return retval else: return proc(txn)
def query(self, obj, operator=None): # Get the complete current value via the base class interface. value = self._query(obj) if value is None: return any.to_any(value) # Don't apply an operator if the value is already a CORBA Any, which # should only occur in the case of a (legacy) user callback. if isinstance(value, CORBA.Any): return value # Attempt to apply the operator to the returned value. try: if operator in ("[]", "[*]"): value = self._getDefaultOperator(value, operator) elif operator == "[?]": value = self._getKeysOperator(value, operator) return any.to_any(check_type_for_long(value)) elif operator == "[@]": value = self._getKeyValuePairsOperator(value, operator) return any.to_any(check_type_for_long(value)) elif operator == "[#]": value = len(self._getDefaultOperator(value, operator)) return any.to_any(check_type_for_long(value)) elif operator != None: value = self._getSliceOperator(value, operator) except Exception, e: raise AttributeError, "error processing operator '%s': '%s' %s" % (operator, e, "\n".join(traceback.format_tb(sys.exc_traceback))) # At this point, value must be a normal sequence, so we can use the # standard conversion routine. return self._toAny(value)
def print_exc(limit=None, file=None): """Shorthand for 'print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)'. (In fact, it uses sys.exc_info() to retrieve the same information in a thread-safe way.)""" if file is None: file = sys.stderr try: etype, value, tb = sys.exc_info() print_exception(etype, value, tb, limit, file) finally: etype = value = tb = None
def run_campaign(test_campaign, get_interactive_session, verb=2): passed=failed=0 if test_campaign.preexec: test_campaign.preexec_output = get_interactive_session(test_campaign.preexec.strip())[0] for testset in test_campaign: for t in testset: t.output,res = get_interactive_session(t.test.strip()) the_res = False try: if res is None or res: the_res= True except Exception,msg: t.output+="UTscapy: Error during result interpretation:\n" t.output+="".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,)) if the_res: t.res = True res = "passed" passed += 1 else: t.res = False res = "failed" failed += 1 t.result = res if verb > 1: print >>sys.stderr,"%(result)6s %(crc)s %(name)s" % t test_campaign.passed = passed test_campaign.failed = failed if verb: print >>sys.stderr,"Campaign CRC=%(crc)s SHA=%(sha)s" % test_campaign print >>sys.stderr,"PASSED=%i FAILED=%i" % (passed, failed) #### INFO LINES ####
def formatExceptionTrace(e): newStr = "".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback)) return newStr
def run_campaign(test_campaign, get_interactive_session, verb=2): passed=failed=0 if test_campaign.preexec: test_campaign.preexec_output = get_interactive_session(test_campaign.preexec.strip())[0] for testset in test_campaign: for t in testset: t.output,res = get_interactive_session(t.test.strip()) the_res = False try: if res is None or res: the_res= True except Exception as msg: t.output+="UTscapy: Error during result interpretation:\n" t.output+="".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,)) if the_res: t.res = True res = "passed" passed += 1 else: t.res = False res = "failed" failed += 1 t.result = res if verb > 1: print("%(result)6s %(crc)s %(name)s" % t, file = sys.stderr) test_campaign.passed = passed test_campaign.failed = failed if verb: print("Campaign CRC=%(crc)s SHA=%(sha)s" % test_campaign, file = sys.stderr) print("PASSED=%i FAILED=%i" % (passed, failed), file = sys.stderr) #### INFO LINES ####
def _report_exception(self): """Internal function.""" import sys exc, val, tb = sys.exc_type, sys.exc_value, sys.exc_traceback root = self._root() root.report_callback_exception(exc, val, tb)
def test(): import sys if sys.argv[1:]: repository = sys.argv[1] else: repository = "." rl = None wl = None try: print "attempting write lock ..." wl = WriteLock(repository) print "got it." wl.unlock() print "attempting read lock ..." rl = ReadLock(repository) print "got it." rl.unlock() finally: print [1] sys.exc_traceback = None print [2] if rl: rl.unlock() print [3] if wl: wl.unlock() print [4] rl = None print [5] wl = None print [6]
def run_campaign(test_campaign, get_interactive_session, verb=2): passed=failed=0 if test_campaign.preexec: test_campaign.preexec_output = get_interactive_session(test_campaign.preexec.strip())[0] for testset in test_campaign: for t in testset: t.output,res = get_interactive_session(t.test.strip()) the_res = False try: if res is None or res: the_res= True except Exception,msg: t.output+="UTscapy: Error during result interpretation:\n" t.output+="".join(traceback.format_exception(sys.exc_type, sys.exc_value, sys.exc_traceback,)) if the_res: t.res = True res = "passed" passed += 1 else: t.res = False res = "failed" failed += 1 t.result = res if verb > 1: print >>sys.stderr,"%(result)6s %(crc)s %(name)s" % t test_campaign.passed = passed test_campaign.failed = failed if verb: print >>sys.stderr,"Campaign CRC=%(crc)s SHA=%(sha)s" % test_campaign print >>sys.stderr,"PASSED=%i FAILED=%i" % (passed, failed) return failed #### INFO LINES ####
def currentframe(): """Return the frame object for the caller's stack frame.""" try: raise 'catch me' except: return sys.exc_traceback.tb_frame.f_back #@UndefinedVariable
def trace(context=1): """Return a list of records for the stack below the current exception.""" return getinnerframes(sys.exc_traceback, context) #@UndefinedVariable