我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.exc_type()。
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + " \n" arcMsg = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n" PrintMsg(theMsg, 2) PrintMsg(arcMsg, 2) except: PrintMsg("Unhandled error in errorMsg method", 2) #======================================================================================================================================
def _dorequest(self, rf, wf): rp = pickle.Unpickler(rf) try: request = rp.load() except EOFError: return 0 if self._verbose > 1: print "Got request: %s" % repr(request) try: methodname, args, id = request if '.' in methodname: reply = (None, self._special(methodname, args), id) elif methodname[0] == '_': raise NameError, "illegal method name %s" % repr(methodname) else: method = getattr(self, methodname) reply = (None, apply(method, args), id) except: reply = (sys.exc_type, sys.exc_value, id) if id < 0 and reply[:2] == (None, None): if self._verbose > 1: print "Suppress reply" return 1 if self._verbose > 1: print "Send reply: %s" % repr(reply) wp = pickle.Pickler(wf) wp.dump(reply) return 1
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 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 format_exception(tb_type=None, tb_value=None, tb=None): """ Get the usual traceback information, followed by a listing of all the local variables in each frame. Based on: code.activestate.com/recipes/52215-get-more-information-from-tracebacks """ import sys import traceback if tb_type is None: tb_type = sys.exc_type if tb_value is None: tb_value = sys.exc_value if tb is None: tb = sys.exc_info()[2] retval = traceback.format_exception(tb_type, tb_value, tb) + ["\n"] while tb.tb_next: tb = tb.tb_next stack = [] f = tb.tb_frame while f: stack.append(f) f = f.f_back stack.reverse() retval.append("Local variables (most recent frame last):\n") for frame in stack: retval.append(" Frame %s, File \"%s\", line %s:\n" % (frame.f_code.co_name, frame.f_code.co_filename, frame.f_lineno)) for key, value in frame.f_locals.items(): if key.startswith("__"): continue #We have to be careful not to cause a new error in our error #handler! Calling str() on an unknown object could cause an #error we don't want. try: line = " %s = %s\n" % (key, str(value)) except: line = " %s = %s\n" % (key, "<ERROR PRINTING VALUE>") retval.append(line) return retval
def handle_requests(wait_time = None, callback = None): global abort abort = false if pyro_daemon is None: raise Pyro.errors.PyroError("There is no daemon with which to handle requests") return if wait_time: start = time.time() while not abort: try: pyro_daemon.handleRequests(wait_time) if wait_time: now = time.time() if callback and now - start > wait_time: callback() start = now elif callback: callback() except Exception, msg: if verbose: print "Error:", sys.exc_type, msg abort = true except: abort = true return abort
def handle_requests(wait_time = None, callback = None): global abort abort = false if pyro_daemon is None: raise Error("There is no daemon with which to handle requests") if wait_time: start = time.time() while not abort: try: pyro_daemon.handleRequests(wait_time) if wait_time: now = time.time() if callback and now - start > wait_time: callback() start = now elif callback: callback() # ignore socket and select errors, they are often transient except socket.error: pass except Exception, msg: if verbose: print "Error:", sys.exc_type, msg abort = true except: abort = true return abort
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value) PrintMsg(theMsg, 2) except: PrintMsg("Unhandled error in errorMsg method", 2) pass ## ===================================================================================
def updateParameters(self): """Modify the values and properties of parameters before internal validation is performed. This method is called whenever a parameter has been changed.""" try: if self.params[0].value and not self.params[0].hasBeenValidated: # clear the other parameters upon change of input layer self.params[1].value = "" rootDir = str(self.params[0].value) if os.path.isdir(rootDir) and rootDir.find('gdb') == -1 : #self.params[2].enabled = True #self.params[3].enabled = False valLst = [] rootLst = os.listdir(rootDir) for e in rootLst: if os.path.isdir(rootDir + os.sep + e) and len(e) == 5: if os.path.isdir(rootDir + os.sep + e) and len(e) == 5: arcpy.env.workspace = (rootDir + os.sep + e) fLst = arcpy.ListFeatureClasses() fStr = str(fLst) if fStr.find('_a.shp') <> -1 and fStr.find('_b.shp') <> -1\ and fStr.find('_c.shp') <> -1 and fStr.find('_d.shp') <> -1\ and fStr.find('_l.shp') <> -1 and fStr.find('_p.shp') <> -1: if not e.upper() in valLst: valLst.append(e) valLst.sort() self.params[1].filter.list = valLst except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] #self.params[2].value = tbinfo + " \n" + str(sys.exc_type) + ": " + str(sys.exc_value) #self.params[4].value = "_".join(valList) return
def updateMessages(self): """Modify the messages created by internal validation for each tool parameter. This method is called after internal validation.""" try: # If there were bad areasymbol values, throw an error to the first parameter. Tried assigning the 3rd paramater # the error but it didn't take. if str(self.params[3].value).find("The following OID records") > -1: self.params[0].setErrorMessage(self.params[3].value) #self.params[0].setErrorMessage("AREASYMBOL Error for the following OID record(s)") if self.params[0].value and not self.params[3].value: env.workspace = self.params[0].value fcList = arcpy.ListFeatureClasses("SAPOLYGON", "Polygon") if len(fcList) == 0: self.params[0].setErrorMessage("SAPOLYGON layer is missing from RTSD Feature Dataset") sapolyFC = os.path.join(env.workspace,"SAPOLYGON") if len([field for field in arcpy.ListFields(sapolyFC,"AREASYMBOL")]) == 0: self.params[0].setErrorMessage("SAPOLYGON layer is missing AREASYMBOL fileld") for fld in self.params[2].filter.list: if fld.find(' ') > -1: self.params[2].setErrorMessage("Error in AREASYMBOL value(s) in SAPOLYGON layer") if not len(fld) == 5: self.params[2].setErrorMessage("AREASYMBOL Value(s) Error! All Areasymbols must be 5 digits") return except: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] self.params[0].value = tbinfo + " \n" + str(sys.exc_type) + ": " + str(sys.exc_value) return
def errorMsg(): tb = sys.exc_info()[2] l = traceback.format_tb(tb) l.reverse() tbinfo = "".join(l) AddMsgAndPrint("\n\n----------ERROR Start-------------------",2) AddMsgAndPrint("Traceback Info: \n" + tbinfo + "Error Info: \n " + str(sys.exc_type)+ ": " + str(sys.exc_value) + "",2) AddMsgAndPrint("----------ERROR End-------------------- \n",2) ## ================================================================================================================
def print_exception(): tb = sys.exc_info()[2] l = traceback.format_tb(tb) l.reverse() tbinfo = "".join(l) AddMsgAndPrint("\n\n----------ERROR Start-------------------",2) AddMsgAndPrint("Traceback Info: \n" + tbinfo + "Error Info: \n " + str(sys.exc_type)+ ": " + str(sys.exc_value) + "",2) AddMsgAndPrint("----------ERROR End-------------------- \n",2) ## ================================================================================================================
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) AddMsgAndPrint(theMsg, 2) except: AddMsgAndPrint("Unhandled error in unHandledException method", 2) pass ## ===================================================================================
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) PrintMsg(theMsg, 2) except: PrintMsg("Unhandled error in errorMsg method", 2) pass ## ===================================================================================
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) PrintMsg(theMsg, 2) except: PrintMsg("Unhandled error in unHandledException method", 2) pass ## ===================================================================================
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + "\n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + "\n" PrintMsg(theMsg, 2) except: PrintMsg("Unhandled error in errorMsg method", 2) pass ## ===================================================================================
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + " \n" AddMsgAndPrint(theMsg, 2) except: AddMsgAndPrint("Unhandled error in errorMsg method", 2) pass ## ================================================================================================================
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + " \n" arcMsg = "ArcPy ERRORS:\n" + arcpy.GetMessages(2) + "\n" PrintMsg(theMsg, 2) PrintMsg(arcMsg, 2) except: PrintMsg("Unhandled error in errorMsg method", 2)
def print_exception(): tb = sys.exc_info()[2] l = traceback.format_tb(tb) l.reverse() tbinfo = "".join(l) AddMsgAndPrint("\n\n----------ERROR Start-------------------",2) AddMsgAndPrint("Traceback Info: \n" + tbinfo + "Error Info: \n " + str(sys.exc_type)+ ": " + str(sys.exc_value) + "",2) AddMsgAndPrint("----------ERROR End-------------------- \n\n",2) ## ================================================================================================================
def errorMsg(): try: tb = sys.exc_info()[2] tbinfo = traceback.format_tb(tb)[0] theMsg = tbinfo + " \n" + str(sys.exc_type)+ ": " + str(sys.exc_value) + " \n" PrintMsg(theMsg, 2) except: PrintMsg("Unhandled error in errorMsg method", 2) pass ## ===================================================================================
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 test_0(self): b = "sys.exc_type" a = "sys.exc_info()[0]" self.check(b, a)
def test_3(self): b = "sys.exc_type # Foo" a = "sys.exc_info()[0] # Foo" self.check(b, a)
def test_4(self): b = "sys. exc_type" a = "sys. exc_info()[0]" self.check(b, a)
def test_5(self): b = "sys .exc_type" a = "sys .exc_info()[0]" self.check(b, a)
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)