我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.exc_value()。
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 error(xml): """ Test error handling. >>> error("foo").position (1, 0) >>> error("<tag>&foo;</tag>").position (1, 5) >>> error("foobar<").position (1, 6) """ try: ET.XML(xml) except ET.ParseError: return sys.exc_value # doesn't work with lxml.etree -> different positions
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 __snd_request(self, method, uri, headers={}, body='', eh=1): try: h = HTTP() h.connect(self.host, self.port) h.putrequest(method, uri) for n, v in headers.items(): h.putheader(n, v) if eh: h.endheaders() if body: h.send(body) ver, code, msg, hdrs = h.getreply() data = h.getfile().read() h.close() except Exception: raise NotAvailable(sys.exc_value) return http_response(ver, code, msg, hdrs, data) # HTTP methods
def sqlite3_conn(database): try: conn = sqlite3.connect(database) except sqlite3.Error: print >> sys.stderr, """\ There was a problem connecting to Database: %s The error leading to this problem was: %s It's possible that this database is broken or permission denied. If you cannot solve this problem yourself, please mail to: %s """ % (database, sys.exc_value, AUTHOR_MAIL) sys.exit(1) else: return conn
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 _marshaled_dispatch(self, data, dispatch_method=None, path=None): """Dispatches an JSON-RPC method from marshalled (JSON) data. JSON-RPC methods are dispatched from the marshalled (JSON) data using the _dispatch method and the result is returned as marshalled data. For backwards compatibility, a dispatch function can be provided as an argument (see comment in SimpleJSONRPCRequestHandler.do_POST) but overriding the existing method through subclassing is the prefered means of changing method dispatch behavior. """ rawreq = json.loads(data, object_hook=JSONDecoder()) req_id = rawreq.get('id', 0) method = rawreq['method'] params = rawreq.get('params', []) response = {'id': req_id} try: # generate response if dispatch_method is not None: response['result'] = dispatch_method(method, params) else: response['result'] = self._dispatch(method, params) except (UserError, UserWarning, NotLogged, ConcurrencyException), exception: response['error'] = exception.args except Exception: tb_s = ''.join(traceback.format_exception(*sys.exc_info())) for path in sys.path: tb_s = tb_s.replace(path, '') # report exception back to server response['error'] = (str(sys.exc_value), tb_s) return json.dumps(response, cls=JSONEncoder)
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 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 __init__(self): if self.info is not None: return info = [] try: #XXX: Bad style to use so long `try:...except:...`. Fix it! import _winreg prgx = re.compile(r"family\s+(?P<FML>\d+)\s+model\s+(?P<MDL>\d+)"\ "\s+stepping\s+(?P<STP>\d+)",re.IGNORECASE) chnd=_winreg.OpenKey(_winreg.HKEY_LOCAL_MACHINE, self.pkey) pnum=0 while 1: try: proc=_winreg.EnumKey(chnd,pnum) except _winreg.error: break else: pnum+=1 info.append({"Processor":proc}) phnd=_winreg.OpenKey(chnd,proc) pidx=0 while True: try: name,value,vtpe=_winreg.EnumValue(phnd,pidx) except _winreg.error: break else: pidx=pidx+1 info[-1][name]=value if name=="Identifier": srch=prgx.search(value) if srch: info[-1]["Family"]=int(srch.group("FML")) info[-1]["Model"]=int(srch.group("MDL")) info[-1]["Stepping"]=int(srch.group("STP")) except: print sys.exc_value,'(ignoring)' self.__class__.info = info
def ScanFiles(directory, signatures, minimumEntropy): try: if os.path.isdir(directory): for entry in os.listdir(directory): ScanFiles(os.path.join(directory, entry), signatures, minimumEntropy) else: ScanFile(directory, signatures, minimumEntropy) except WindowsError: if sys.exc_value.winerror == 5: pass else: print(sys.exc_value) exit()
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)