当前位置: 首页>>代码示例>>Python>>正文


Python exceptions.ValueError方法代码示例

本文整理汇总了Python中exceptions.ValueError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ValueError方法的具体用法?Python exceptions.ValueError怎么用?Python exceptions.ValueError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在exceptions的用法示例。


在下文中一共展示了exceptions.ValueError方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: ip_address_from_address

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def ip_address_from_address(address):
    try:
        ip_address = netaddr.IPAddress(address)
    except ValueError as e:
        # address contains a CIDR prefix, netmask, or hostmask.
        e.message = ('invalid IP address: %(address)s (detected CIDR, netmask,'
                     ' hostmask, or subnet)') % {'address': address}
        raise
    except netaddr.AddrFormatError as e:
        # address is not an IP address represented in an accepted string
        # format.
        e.message = ("invalid IP address: '%(address)s' (failed to detect a"
                     " valid IP address)") % {'address': address}
        raise

    if ip_address.version == 4:
        return ip_address
    else:
        raise NotSupported(
            ('invalid IP address: %(address)s (Internet Protocol version'
             ' %(version)s is not supported)') % {
                'address': address,
                'version': ip_address.version}) 
开发者ID:dsp-jetpack,项目名称:JetPack,代码行数:25,代码来源:discover_nodes.py

示例2: dump

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def dump(self, indentation=0):
        """Returns a string representation of the structure."""
    
        dump = []
        
        dump.append('[%s]' % self.name)

        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:

                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))

                dump.append('%-30s %s' % (key+':', val_str)) 
开发者ID:Ice3man543,项目名称:MalScan,代码行数:26,代码来源:pefile.py

示例3: ip_set_from_idrac

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def ip_set_from_idrac(idrac):
    range_bounds = idrac.split('-')

    if len(range_bounds) == 2:
        start, end = range_bounds
        ip_set = ip_set_from_address_range(start, end)
    elif len(range_bounds) == 1:
        ip_set = ip_set_from_address(range_bounds[0])
    else:
        # String contains more than one (1) dash.
        raise ValueError(
            ('invalid IP range: %(idrac)s (contains more than one hyphen)') % {
                'idrac': idrac})

    return ip_set 
开发者ID:dsp-jetpack,项目名称:JetPack,代码行数:17,代码来源:discover_nodes.py

示例4: ip_set_from_address_range

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def ip_set_from_address_range(start, end):
    try:
        start_ip_address = ip_address_from_address(start)
        end_ip_address = ip_address_from_address(end)
    except (NotSupported, ValueError) as e:
        raise ValueError(
            ('invalid IP range: %(start)s-%(end)s (%(message)s)') %
            {
                'start': start,
                'end': end,
                'message': e.message})
    except netaddr.AddrFormatError as e:
        raise ValueError(
            ("invalid IP range: '%(start)s-%(end)s' (%(message)s)") %
            {
                'start': start,
                'end': end,
                'message': e.message})

    if start_ip_address > end_ip_address:
        raise ValueError(
            ('invalid IP range: %(start)s-%(end)s (lower bound IP greater than'
             ' upper bound)') %
            {
                'start': start,
                'end': end})

    ip_range = netaddr.IPRange(start_ip_address, end_ip_address)

    return netaddr.IPSet(ip_range) 
开发者ID:dsp-jetpack,项目名称:JetPack,代码行数:32,代码来源:discover_nodes.py

示例5: ip_set_from_address

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def ip_set_from_address(address):
    ip_set = netaddr.IPSet()

    try:
        ip_address = ip_address_from_address(address)
        ip_set.add(ip_address)
    except ValueError:
        ip_network = ip_network_from_address(address)
        ip_set.update(ip_network.iter_hosts())

    return ip_set 
开发者ID:dsp-jetpack,项目名称:JetPack,代码行数:13,代码来源:discover_nodes.py

示例6: get_config

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def get_config(self, section=None, option=None):
        """
        Sends the request to get the matching configuration.

        :param section: the optional name of the section.
        :param option: the optional option within the section.
        :return: dictionary containing the configuration.
        """

        if section is None and option is not None:
            raise ValueError('--section not specified')

        path = self.CONFIG_BASEURL
        if section is not None and option is None:
            path += '/' + section
        elif section is not None and option is not None:
            path += '/'.join(['', section, option])

        url = build_url(choice(self.list_hosts), path=path)

        r = self._send_request(url, type='GET')
        if r.status_code == codes.ok:
            return r.json()
        else:
            exc_cls, exc_msg = self._get_exception(headers=r.headers, status_code=r.status_code, data=r.content)
            raise exc_cls(exc_msg) 
开发者ID:rucio,项目名称:rucio,代码行数:28,代码来源:configclient.py

示例7: next_id

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def next_id(self, time_msecs):
        now = int(time_msecs)
        duplicateTime = (now == self.lastPushTime)
        self.lastPushTime = now
        timeStampChars = [''] * 8

        for i in range(7, -1, -1):
            timeStampChars[i] = self.PUSH_CHARS[now % 64]
            now = int(now / 64)

        if (now != 0):
            raise ValueError('We should have converted the entire timestamp.')

        uid = ''.join(timeStampChars)

        if not duplicateTime:
            for i in range(12):
                self.lastRandChars[i] = int(random.random() * 64)
        else:
            # If the timestamp hasn't changed since last push, use the
            # same random number, except incremented by 1.
            for i in range(11, -1, -1):
                if self.lastRandChars[i] == 63:
                    self.lastRandChars[i] = 0
                else:
                    break
            self.lastRandChars[i] += 1

        for i in range(12):
            uid += self.PUSH_CHARS[self.lastRandChars[i]]

        if len(uid) != 20:
            raise ValueError('Length should be 20.')
        return uid 
开发者ID:danvk,项目名称:oldnyc,代码行数:36,代码来源:firebase_pushid.py

示例8: dump

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def dump(self, indentation=0):
        """Returns a string representation of the structure."""
        
        dump = []
        
        dump.append('[%s]' % self.name)
        
        # Refer to the __set_format__ method for an explanation
        # of the following construct.
        for keys in self.__keys__:
            for key in keys:
                
                val = getattr(self, key)
                if isinstance(val, int) or isinstance(val, long):
                    val_str = '0x%-8X' % (val)
                    if key == 'TimeDateStamp' or key == 'dwTimeStamp':
                        try:
                            val_str += ' [%s UTC]' % time.asctime(time.gmtime(val))
                        except exceptions.ValueError, e:
                            val_str += ' [INVALID TIME]'
                else:
                    val_str = ''.join(filter(lambda c:c != '\0', str(val)))
                
                dump.append('0x%-8X 0x%-3X %-30s %s' % (
                    self.__field_offsets__[key] + self.__file_offset__, 
                    self.__field_offsets__[key], key+':', val_str)) 
开发者ID:Lithium876,项目名称:ConTroll_Remote_Access_Trojan,代码行数:28,代码来源:pefile.py

示例9: parse_command

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def parse_command(command):
    """
    Parse the command portion of a gcode line, and return a dictionary of found codes and their respective values, and a list of found flags. Codes with integer values will have an integer type, while codes with float values will have a float type
    @param string command Command portion of a gcode line
    @return tuple containing a dict of codes, list of flags.
    """
    codes = {}
    flags = []

    pairs = command.split()
    for pair in pairs:
        code = pair[0]

        # If the code is not a letter, this is an error.
        if not code.isalpha():
            gcode_error = makerbot_driver.Gcode.InvalidCodeError()
            gcode_error.values['InvalidCode'] = code
            raise gcode_error

        # Force the code to be uppercase.
        code = code.upper()

        # If the code already exists, this is an error.
        if code in codes.keys():
            gcode_error = makerbot_driver.Gcode.RepeatCodeError()
            gcode_error.values['RepeatedCode'] = code
            raise gcode_error

        # Don't allow both G and M codes in the same line
        if (code == 'G' and 'M' in codes.keys()) or \
           (code == 'M' and 'G' in codes.keys()):
            raise makerbot_driver.Gcode.MultipleCommandCodeError()

        # If the code doesn't have a value, we consider it a flag, and set it to true.
        if len(pair) == 1:
            flags.append(code)

        else:
            try:
                codes[code] = int(pair[1:])
            except exceptions.ValueError:
                codes[code] = float(pair[1:])

    return codes, flags 
开发者ID:AstroPrint,项目名称:AstroBox,代码行数:46,代码来源:Utils.py

示例10: test_proxy

# 需要导入模块: import exceptions [as 别名]
# 或者: from exceptions import ValueError [as 别名]
def test_proxy(item):
	try:
		item['port'] = int(item['port'])
	except ValueError:
		return None
	if item['type'] == 'http':
		proxyHandler = urllib2.ProxyHandler({'http':'http://%s:%s' % (item['ip'], item['port']), 'https':'http://%s:%s' % (item['ip'], item['port'])})  
		opener = urllib2.build_opener(proxyHandler)
		opener.addheaders = {
			'Accept-Encoding': 'gzip',
			'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6',
			'User-Agent': 'Mozilla/5.0 (compatible; WOW64; MSIE 10.0; Windows NT 6.2)',
			'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
			'Cache-Control': 'max-age=0'
		}.items()
		try:
			req = urllib2.Request('http://httpbin.org/get')
			begin = time.time()
			resp = opener.open(req)
			content = resp.read()
			item['speed'] = int((time.time() - begin) * 1000)
			content = json.loads(content)
			if content['origin'].find(localhost) != -1:
				# print '\t[Leak Header] X-Forwarded-For: %s' % content['origin']
				item['type'] = 'transparent'
				return item
			if len(content['origin'].split(',')) > 1:
				# print '\t[Leak Header] X-Forwarded-For: %s' % content['origin']
				item['type'] = 'anonymous'
				return item
			# logger.error('ip: %s' % item['ip'])
			# for key in content['headers']:
			# 	logger.error('%s: %s' % (key, content['headers'][key]))
			for key in content['headers']:
				if content['headers'][key].find(localhost) != -1:
					# print '\t[Leak Header] %s: %s' % (key, content['headers'][key])
					item['type'] = 'transparent'
					return item
				if key.lower() in proxy_headers:
					# print '\t[Leak Header] %s: %s' % (key, content['headers'][key])
					item['type'] = 'anonymous'
			if item['type'] == 'http':
				item['type'] = 'high'
			return item
		except exceptions.ValueError, error:
			# print 'host seems to be a proxy with limitation'
			# print error
			pass
		except httplib.BadStatusLine, error:
			# print error
			pass 
开发者ID:xelzmm,项目名称:proxy_server_crawler,代码行数:53,代码来源:pipelines.py


注:本文中的exceptions.ValueError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。