Python exceptions.Exception() Examples
The following are 30
code examples of exceptions.Exception().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
exceptions
, or try the search function
.
Example #1
Source File: DataManager.py From Caffe-Python-Data-Layer with BSD 2-Clause "Simplified" License | 6 votes |
def load_all(self): """The function to load all data and labels Give: data: the list of raw data, needs to be decompressed (e.g., raw JPEG string) labels: numpy array, with each element is a string """ start = time.time() print("Start Loading Data from BCF {}".format( 'MEMORY' if self._bcf_mode == 'MEM' else 'FILE')) self._labels = np.loadtxt(self._label_fn).astype(str) if self._bcf.size() != self._labels.shape[0]: raise Exception("Number of samples in data" "and labels are not equal") else: for idx in range(self._bcf.size()): datum_str = self._bcf.get(idx) self._data.append(datum_str) end = time.time() print("Loading {} samples Done: Time cost {} seconds".format( len(self._data), end - start)) return self._data, self._labels
Example #2
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_str2(self): # verify we can assign to sys.exc_* sys.exc_traceback = None sys.exc_value = None sys.exc_type = None self.assertEqual(str(Exception()), '') @skipUnlessIronPython() def test_array(self): import System try: a = System.Array() except Exception, e: self.assertEqual(e.__class__, TypeError) else:
Example #3
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 6 votes |
def test_module_exceptions(self): """verify exceptions in modules are like user defined exception objects, not built-in types.""" # these modules have normal types... normal_types = ['sys', 'clr', 'exceptions', '__builtin__', '_winreg', 'mmap', 'nt', 'posix'] builtins = [x for x in sys.builtin_module_names if x not in normal_types ] for module in builtins: mod = __import__(module) for attrName in dir(mod): val = getattr(mod, attrName) if isinstance(val, type) and issubclass(val, Exception): if "BlockingIOError" not in repr(val): self.assertTrue(repr(val).startswith("<class ")) val.x = 2 self.assertEqual(val.x, 2) else: self.assertTrue(repr(val).startswith("<type "))
Example #4
Source File: __init__.py From presto-admin with Apache License 2.0 | 6 votes |
def determine_jdk_directory(cluster): """ Return the directory where the JDK is installed. For example if the JDK is located in /usr/java/jdk1.8_91, then this method will return the string 'jdk1.8_91'. This method will throw an Exception if the number of JDKs matching the /usr/java/jdk* pattern is not equal to 1. :param cluster: cluster on which to search for the JDK directory """ number_of_jdks = cluster.exec_cmd_on_host(cluster.master, 'bash -c "ls -ld /usr/java/j*| wc -l"') if int(number_of_jdks) != 1: raise Exception('The number of JDK directories matching /usr/java/jdk* is not 1') output = cluster.exec_cmd_on_host(cluster.master, 'ls -d /usr/java/j*') return output.split(os.path.sep)[-1].strip('\n')
Example #5
Source File: split.py From PiBunny with MIT License | 5 votes |
def __init__(self, pcapObj): # Query the type of the link and instantiate a decoder accordingly. datalink = pcapObj.datalink() if pcapy.DLT_EN10MB == datalink: self.decoder = EthDecoder() elif pcapy.DLT_LINUX_SLL == datalink: self.decoder = LinuxSLLDecoder() else: raise Exception("Datalink type not supported: " % datalink) self.pcap = pcapObj self.connections = {}
Example #6
Source File: DataManager.py From Caffe-Python-Data-Layer with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, param): self._source_fn = param.get('source') self._label_fn = param.get('labels') # bcf_mode: either FILE or MEM, default=FILE self._bcf_mode = param.get('bcf_mode', 'FILE') if not os.path.isfile(self._source_fn) or \ not os.path.isfile(self._label_fn): raise Exception("Either Source of Label file does not exist") else: if self._bcf_mode == 'MEM': self._bcf = bcf_store_memory(self._source_fn) elif self._bcf_mode == 'FILE': self._bcf = bcf_store_file(self._source_fn) self._data = [] self._labels = []
Example #7
Source File: ProxyHelper.py From Malicious_Domain_Whois with GNU General Public License v3.0 | 5 votes |
def _test_proxyip(self,ip): try: proxy={'http':ip} #print "正在测试代理" res=requests.get("http://www.baidu.com",proxies=proxy,timeout=1) if res.content.find("百度一下")!=-1: return True else: return False except Exception,e: #print e return False #添加代理ip并筛选
Example #8
Source File: exception_util.py From RevitBatchProcessor with GNU General Public License v3.0 | 5 votes |
def LogOutputErrorDetails(exception, output_, verbose=True): output = global_test_mode.PrefixedOutputForGlobalTestMode(output_, EXCEPTION_MESSAGE_HANDLER_PREFIX) exceptionMessage = ( str(exception.message) if isinstance(exception, exceptions.Exception) else str(exception.Message) if isinstance(exception, System.Exception) else str.Empty ) output() output("Exception: [" + type(exception).__name__ + "] " + exceptionMessage) try: clsException = GetClrException(exception) if clsException is not None: clsExceptionType = clr.GetClrType(type(clsException)) output(".NET exception: [" + str(clsExceptionType.Name) + "] " + str(clsException.Message)) if verbose: interpretedFrameInfo = GetInterpretedFrameInfo(clsException.Data) if interpretedFrameInfo is not None: output() output("Further exception information:") output() for i in interpretedFrameInfo: if str(i) != "CallSite.Target": output("\t" + str(i)) except: output("Could not obtain further exception information.") return
Example #9
Source File: exception_util.py From RevitBatchProcessor with GNU General Public License v3.0 | 5 votes |
def GetClrException(exception): return ( exception.clsException if isinstance(exception, exceptions.Exception) else exception if isinstance(exception, System.Exception) else None )
Example #10
Source File: rsync_weak_auth.py From xunfengES with GNU General Public License v3.0 | 5 votes |
def check(host, port, timeout=5): info = '' not_unauth_list = [] weak_auth_list = [] userlist = ['test', 'root', 'www', 'web', 'rsync', 'admin'] if __name__ == '__main__': passwdlist = ['test', 'neagrle'] else: passwdlist = PASSWORD_DIC try: rwc = RsyncWeakCheck(host,port) for path_name in rwc.get_all_pathname(): ret = rwc.is_path_not_auth(path_name) if ret == 0: not_unauth_list.append(path_name) elif ret == 1: for username, passwd in product(userlist, passwdlist): try: res = rwc.weak_passwd_check(path_name, username, passwd) if res: weak_auth_list.append((path_name, username, passwd)) except VersionNotSuppError as e: # TODO fengxun error support pass except Exception, e: pass
Example #11
Source File: rsync_weak_auth.py From xunfengES with GNU General Public License v3.0 | 5 votes |
def check(host, port, timeout=5): info = '' not_unauth_list = [] weak_auth_list = [] userlist = ['test', 'root', 'www', 'web', 'rsync', 'admin'] if __name__ == '__main__': passwdlist = ['test', 'neagrle'] else: passwdlist = PASSWORD_DIC try: rwc = RsyncWeakCheck(host,port) for path_name in rwc.get_all_pathname(): ret = rwc.is_path_not_auth(path_name) if ret == 0: not_unauth_list.append(path_name) elif ret == 1: for username, passwd in product(userlist, passwdlist): try: res = rwc.weak_passwd_check(path_name, username, passwd) if res: weak_auth_list.append((path_name, username, passwd)) except VersionNotSuppError as e: # TODO fengxun error support pass except Exception, e: pass
Example #12
Source File: backtest.py From Crypto_trading_robot with MIT License | 5 votes |
def not_supported(self): raise exceptions.Exception('not supported in backtesting')
Example #13
Source File: Utility.py From p2pool-n with GNU General Public License v3.0 | 5 votes |
def loadFromURL(self, url): """Load an xml file from a URL and return a DOM document.""" if isfile(url) is True: file = open(url, 'r') else: file = urlopen(url) try: result = self.loadDocument(file) except Exception, ex: file.close() raise ParseError(('Failed to load document %s' %url,) + ex.args)
Example #14
Source File: recipe-144838.py From code with MIT License | 5 votes |
def getCallString(level): #this gets us the frame of the caller and will work #in python versions 1.5.2 and greater (there are better #ways starting in 2.1 try: raise FakeException("this is fake") except Exception, e: #get the current execution frame f = sys.exc_info()[2].tb_frame #go back as many call-frames as was specified
Example #15
Source File: trace_data_unittest.py From Jandroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
def testBasicChrome(self): builder = trace_data.TraceDataBuilder() builder.AddTraceFor(trace_data.CHROME_TRACE_PART, {'traceEvents': [1, 2, 3]}) d = builder.AsData() self.assertTrue(d.HasTracesFor(trace_data.CHROME_TRACE_PART)) self.assertRaises(Exception, builder.AsData)
Example #16
Source File: trace_data_unittest.py From Jandroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
def testSetTraceForRaisesAfterAsData(self): builder = trace_data.TraceDataBuilder() builder.AsData() self.assertRaises( exceptions.Exception, lambda: builder.AddTraceFor(trace_data.TELEMETRY_PART, {}))
Example #17
Source File: trace_data_unittest.py From Jandroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
def testBasicChrome(self): builder = trace_data.TraceDataBuilder() builder.AddTraceFor(trace_data.CHROME_TRACE_PART, {'traceEvents': [1, 2, 3]}) d = builder.AsData() self.assertTrue(d.HasTracesFor(trace_data.CHROME_TRACE_PART)) self.assertRaises(Exception, builder.AsData)
Example #18
Source File: trace_data_unittest.py From Jandroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
def testSetTraceForRaisesAfterAsData(self): builder = trace_data.TraceDataBuilder() builder.AsData() self.assertRaises( exceptions.Exception, lambda: builder.AddTraceFor(trace_data.TELEMETRY_PART, {}))
Example #19
Source File: trace_data_unittest.py From Jandroid with BSD 3-Clause "New" or "Revised" License | 5 votes |
def testBasicChrome(self): builder = trace_data.TraceDataBuilder() builder.AddTraceFor(trace_data.CHROME_TRACE_PART, {'traceEvents': [1, 2, 3]}) d = builder.AsData() self.assertTrue(d.HasTracesFor(trace_data.CHROME_TRACE_PART)) self.assertRaises(Exception, builder.AsData)
Example #20
Source File: rsync_weak_auth.py From xunfeng with GNU General Public License v3.0 | 5 votes |
def check(host, port, timeout=5): info = '' not_unauth_list = [] weak_auth_list = [] userlist = ['test', 'root', 'www', 'web', 'rsync', 'admin'] if __name__ == '__main__': passwdlist = ['test', 'neagrle'] else: passwdlist = PASSWORD_DIC try: rwc = RsyncWeakCheck(host,port) for path_name in rwc.get_all_pathname(): ret = rwc.is_path_not_auth(path_name) if ret == 0: not_unauth_list.append(path_name) elif ret == 1: for username, passwd in product(userlist, passwdlist): try: res = rwc.weak_passwd_check(path_name, username, passwd) if res: weak_auth_list.append((path_name, username, passwd)) except VersionNotSuppError as e: # TODO fengxun error support pass except Exception, e: pass
Example #21
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_issue1164(self): class error(Exception): pass def f(): raise (error,), 0 self.assertRaises(error, f)
Example #22
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_derived_keyword_args(self): class ED(Exception): def __init__(self, args=''): pass self.assertEqual(type(ED(args='')), ED)
Example #23
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_exception_doc(self): # should be accessible, CPython and IronPython have different strings though. Exception().__doc__ Exception("abc").__doc__
Example #24
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_newstyle_raise(self): # raise a new style exception via raise type, value that returns an arbitrary object class MyException(Exception): def __new__(cls, *args): return 42 try: raise MyException, 'abc' self.assertUnreachable() except Exception, e: self.assertEqual(e, 42)
Example #25
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_nested_exceptions(self): try: raise Exception() except Exception, e: # PushException try: raise TypeError except TypeError, te: # PushException ei = sys.exc_info() # PopException
Example #26
Source File: test_exceptions.py From ironpython2 with Apache License 2.0 | 5 votes |
def test_exception_line_no_with_finally(self): def f(): try: raise Exception() # this line should correspond w/ the number below finally: pass try: f() except Exception, e: tb = sys.exc_info()[2] expected = [24, 29] while tb: self.assertEqual(tb.tb_lineno, expected.pop()) # adding lines will require an update here tb = tb.tb_next
Example #27
Source File: DataManager.py From Caffe-Python-Data-Layer with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, param): self._source_fn = param.get('source') if not os.path.isfile(self._source_fn): raise Exception("Source file does not exist") self._label_fn = param.get('labels', None) self._data = [] self._labels = []
Example #28
Source File: DataManager.py From Caffe-Python-Data-Layer with BSD 2-Clause "Simplified" License | 5 votes |
def __init__(self, param): self._source_fn = param.get('source') self._root = param.get('root', None) self._header = param.get('header', None) if not os.path.isfile(self._source_fn): raise Exception("Source file does not exist") self._data = [] self._labels = []
Example #29
Source File: __init__.py From mgear_dist with MIT License | 4 votes |
def getInfos(level): """Get information from where the method has been fired. Such as module name, method, line number... Args: level (int): Level Returns: str: The info """ try: raise FakeException("this is fake") except Exception: # get the current execution frame f = sys.exc_info()[2].tb_frame # go back as many call-frames as was specified while level >= 0: f = f.f_back level = level - 1 infos = "" # Module Name moduleName = f.f_globals["__name__"] if moduleName != "__ax_main__": infos += moduleName + " | " # Class Name # if there is a self variable in the caller's local namespace then # we'll make the assumption that the caller is a class method obj = f.f_locals.get("self", None) if obj: infos += obj.__class__.__name__ + "::" # Function Name functionName = f.f_code.co_name if functionName != "<module>": infos += functionName + "()" # Line Number lineNumber = str(f.f_lineno) infos += " line " + lineNumber + "" if infos: infos = "[" + infos + "]" return infos
Example #30
Source File: DataManager.py From Caffe-Python-Data-Layer with BSD 2-Clause "Simplified" License | 4 votes |
def load_all(self): """The function to load all data and labels Give: data: the list of raw data, needs to be decompressed (e.g., raw JPEG string) labels: numpy array of string, to support multiple label """ start = time.time() print("Start Loading Data from CSV File {}".format( self._source_fn)) # split csv using both space, tab, or comma sep = '[\s,]+' try: df = pd.read_csv(self._source_fn, sep=sep, engine='python', header=self._header) print("Totally {} rows loaded to parse...".format( len(df.index) )) # parse df to get image file name and label for ln in df.iterrows(): # for each row, the first column is file name, then labels fn_ = ln[1][0] if self._root: fn_ = os.path.join(self._root, fn_) if not os.path.exists(fn_): print("File {} does not exist, skip".format(fn_)) continue # read labels: the first column is image file name # and others are labels (one or more) label_ = ln[1][1:].values if len(label_) == 1: label_ = label_[0] else: label_ = ":".join([str(x) for x in label_.astype(int)]) self._labels.append(str(label_)) # open file as binary and read in with open(fn_, 'rb') as image_fp: datum_str_ = image_fp.read() self._data.append(datum_str_) except: print sys.exc_info()[1], fn_ raise Exception("Error in Parsing input file") end = time.time() self._labels = np.array(self._labels) print("Loading {} samples Done: Time cost {} seconds".format( len(self._data), end - start)) return self._data, self._labels