Python sys.hexversion() Examples

The following are 30 code examples of sys.hexversion(). 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 sys , or try the search function .
Example #1
Source File: Task.py    From 802.11ah-ns3 with GNU General Public License v2.0 6 votes vote down vote up
def __init__(cls,name,bases,dict):
		super(store_task_type,cls).__init__(name,bases,dict)
		name=cls.__name__
		if name.endswith('_task'):
			name=name.replace('_task','')
		if name!='evil'and name!='TaskBase':
			global classes
			if getattr(cls,'run_str',None):
				(f,dvars)=compile_fun(cls.run_str,cls.shell)
				cls.hcode=cls.run_str
				cls.orig_run_str=cls.run_str
				cls.run_str=None
				cls.run=f
				cls.vars=list(set(cls.vars+dvars))
				cls.vars.sort()
			elif getattr(cls,'run',None)and not'hcode'in cls.__dict__:
				cls.hcode=Utils.h_fun(cls.run)
			if sys.hexversion>0x3000000:
				cls.hcode=cls.hcode.encode('iso8859-1','xmlcharrefreplace')
			getattr(cls,'register',classes)[name]=cls 
Example #2
Source File: test_sys.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_implementation(self):
        # This test applies to all implementations equally.

        levels = {'alpha': 0xA, 'beta': 0xB, 'candidate': 0xC, 'final': 0xF}

        self.assertTrue(hasattr(sys.implementation, 'name'))
        self.assertTrue(hasattr(sys.implementation, 'version'))
        self.assertTrue(hasattr(sys.implementation, 'hexversion'))
        self.assertTrue(hasattr(sys.implementation, 'cache_tag'))

        version = sys.implementation.version
        self.assertEqual(version[:2], (version.major, version.minor))

        hexversion = (version.major << 24 | version.minor << 16 |
                      version.micro << 8 | levels[version.releaselevel] << 4 |
                      version.serial << 0)
        self.assertEqual(sys.implementation.hexversion, hexversion)

        # PEP 421 requires that .name be lower case.
        self.assertEqual(sys.implementation.name,
                         sys.implementation.name.lower()) 
Example #3
Source File: ROOT.py    From parliament2 with Apache License 2.0 6 votes vote down vote up
def __setattr2( self, name, value ):     # "running" getattr
    # to allow assignments to ROOT globals such as ROOT.gDebug
      if not name in self.__dict__:
         try:
          # assignment to an existing ROOT global (establishes proxy)
            setattr( self.__class__, name, _root.GetCppGlobal( name ) )
         except LookupError:
          # allow a few limited cases where new globals can be set
            if sys.hexversion >= 0x3000000:
               pylong = int
            else:
               pylong = long
            tcnv = { bool        : 'bool %s = %d;',
                     int         : 'int %s = %d;',
                     pylong      : 'long %s = %d;',
                     float       : 'double %s = %f;',
                     str         : 'string %s = "%s";' }
            try:
               _root.gROOT.ProcessLine( tcnv[ type(value) ] % (name,value) );
               setattr( self.__class__, name, _root.GetCppGlobal( name ) )
            except KeyError:
               pass           # can still assign normally, to the module

    # actual assignment through descriptor, or normal python way
      return super( self.__class__, self ).__setattr__( name, value ) 
Example #4
Source File: XbmcHelpers.py    From kodi with GNU General Public License v3.0 6 votes vote down vote up
def makeAscii(data):
    log(repr(data), 5)
    #if sys.hexversion >= 0x02050000:
    #        return data

    try:
        return data.encode('ascii', "ignore")
    except:
        log("Hit except on : " + repr(data))
        s = u""
        for i in data:
            try:
                i.encode("ascii", "ignore")
            except:
                log("Can't convert character", 4)
                continue
            else:
                s += i

        log(repr(s), 5)
        return s


# This function handles stupid utf handling in python. 
Example #5
Source File: Node.py    From royal-chaos with MIT License 6 votes vote down vote up
def read_json(self,convert=True,encoding='utf-8'):
		import json
		object_pairs_hook=None
		if convert and sys.hexversion<0x3000000:
			try:
				_type=unicode
			except NameError:
				_type=str
			def convert(value):
				if isinstance(value,list):
					return[convert(element)for element in value]
				elif isinstance(value,_type):
					return str(value)
				else:
					return value
			def object_pairs(pairs):
				return dict((str(pair[0]),convert(pair[1]))for pair in pairs)
			object_pairs_hook=object_pairs
		return json.loads(self.read(encoding=encoding),object_pairs_hook=object_pairs_hook) 
Example #6
Source File: errcheck.py    From royal-chaos with MIT License 6 votes vote down vote up
def check_invalid_constraints(self):
	feat=set([])
	for x in list(TaskGen.feats.values()):
		feat.union(set(x))
	for(x,y)in TaskGen.task_gen.prec.items():
		feat.add(x)
		feat.union(set(y))
	ext=set([])
	for x in TaskGen.task_gen.mappings.values():
		ext.add(x.__name__)
	invalid=ext&feat
	if invalid:
		Logs.error('The methods %r have invalid annotations:  @extension <-> @feature/@before_method/@after_method'%list(invalid))
	for cls in list(Task.classes.values()):
		if sys.hexversion>0x3000000 and issubclass(cls,Task.Task)and isinstance(cls.hcode,str):
			raise Errors.WafError('Class %r has hcode value %r of type <str>, expecting <bytes> (use Utils.h_cmd() ?)'%(cls,cls.hcode))
		for x in('before','after'):
			for y in Utils.to_list(getattr(cls,x,[])):
				if not Task.classes.get(y,None):
					Logs.error('Erroneous order constraint %r=%r on task class %r'%(x,y,cls.__name__))
		if getattr(cls,'rule',None):
			Logs.error('Erroneous attribute "rule" on task class %r (rename to "run_str")'%cls.__name__) 
Example #7
Source File: Utils.py    From royal-chaos with MIT License 6 votes vote down vote up
def writef_win32(f,data,m='w',encoding='ISO8859-1'):
	if sys.hexversion>0x3000000 and not'b'in m:
		data=data.encode(encoding)
		m+='b'
	flags=os.O_CREAT|os.O_TRUNC|os.O_WRONLY|os.O_NOINHERIT
	if'b'in m:
		flags|=os.O_BINARY
	if'+'in m:
		flags|=os.O_RDWR
	try:
		fd=os.open(f,flags)
	except OSError:
		raise IOError('Cannot write to %r'%f)
	f=os.fdopen(fd,m)
	try:
		f.write(data)
	finally:
		f.close() 
Example #8
Source File: testShell.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def testComplex(self):
        if sys.hexversion < 0x2030000:
            # no kw-args to dict in 2.2 - not worth converting!
            return
        clsid = pythoncom.MakeIID("{CD637886-DB8B-4b04-98B5-25731E1495BE}")
        ctime, atime, wtime = self._getTestTimes()
        d = dict(cFileName="foo.txt",
                 clsid=clsid,
                 sizel=(1,2),
                 pointl=(3,4),
                 dwFileAttributes = win32con.FILE_ATTRIBUTE_NORMAL,
                 ftCreationTime=ctime,
                 ftLastAccessTime=atime,
                 ftLastWriteTime=wtime,
                 nFileSize=sys_maxsize + 1)
        self._testRT(d) 
Example #9
Source File: strings.py    From testplan with Apache License 2.0 6 votes vote down vote up
def slugify(value):
    """
    Normalizes string, converts to lowercase, removes non-alpha characters,
    and converts spaces to hyphens.

    :param value: string value to slugify
    :type value: ``str``

    :return: slugified string value, suitable as a directory or filename
    :rtype: ``str``
    """
    if sys.hexversion >= 0x30303F0:
        value = unicodedata.normalize("NFKD", value).encode("ascii", "ignore")
        value = re.sub(br"[^\w\s-]", b"", value).strip().lower()
        return re.sub(br"[-\s]+", b"-", value).decode("ascii")
    else:
        value = unicodedata.normalize("NFKD", six.text_type(value)).encode(
            "ascii", "ignore"
        )
        value = six.text_type(re.sub(r"[^\w\s-]", "", value).strip().lower())
        return str(re.sub(r"[-\s]+", "-", value)) 
Example #10
Source File: install_egg_info.py    From python-netsurv with MIT License 6 votes vote down vote up
def finalize_options(self):
        self.set_undefined_options('install_lib',
                                   ('install_dir', 'install_dir'))
        self.set_undefined_options('install',('install_layout','install_layout'))
        if sys.hexversion > 0x2060000:
            self.set_undefined_options('install',('prefix_option','prefix_option'))
        ei_cmd = self.get_finalized_command("egg_info")
        basename = pkg_resources.Distribution(
            None, None, ei_cmd.egg_name, ei_cmd.egg_version
        ).egg_name() + '.egg-info'

        if self.install_layout:
            if not self.install_layout.lower() in ['deb']:
                raise DistutilsOptionError("unknown value for --install-layout")
            self.install_layout = self.install_layout.lower()
            basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '')
        elif self.prefix_option or 'real_prefix' in sys.__dict__:
            # don't modify for virtualenv
            pass
        else:
            basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '')

        self.source = ei_cmd.egg_info
        self.target = os.path.join(self.install_dir, basename)
        self.outputs = [] 
Example #11
Source File: install_egg_info.py    From python-netsurv with MIT License 6 votes vote down vote up
def finalize_options(self):
        self.set_undefined_options('install_lib',
                                   ('install_dir', 'install_dir'))
        self.set_undefined_options('install',('install_layout','install_layout'))
        if sys.hexversion > 0x2060000:
            self.set_undefined_options('install',('prefix_option','prefix_option'))
        ei_cmd = self.get_finalized_command("egg_info")
        basename = pkg_resources.Distribution(
            None, None, ei_cmd.egg_name, ei_cmd.egg_version
        ).egg_name() + '.egg-info'

        if self.install_layout:
            if not self.install_layout.lower() in ['deb']:
                raise DistutilsOptionError("unknown value for --install-layout")
            self.install_layout = self.install_layout.lower()
            basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '')
        elif self.prefix_option or 'real_prefix' in sys.__dict__:
            # don't modify for virtualenv
            pass
        else:
            basename = basename.replace('-py%s' % pkg_resources.PY_MAJOR, '')

        self.source = ei_cmd.egg_info
        self.target = os.path.join(self.install_dir, basename)
        self.outputs = [] 
Example #12
Source File: Utils.py    From royal-chaos with MIT License 6 votes vote down vote up
def readf(fname,m='r',encoding='ISO8859-1'):
	if sys.hexversion>0x3000000 and not'b'in m:
		m+='b'
		f=open(fname,m)
		try:
			txt=f.read()
		finally:
			f.close()
		if encoding:
			txt=txt.decode(encoding)
		else:
			txt=txt.decode()
	else:
		f=open(fname,m)
		try:
			txt=f.read()
		finally:
			f.close()
	return txt 
Example #13
Source File: implementation.py    From nested-dict with MIT License 6 votes vote down vote up
def flatten_nested_items(dictionary):
    """
    Flatten a nested_dict.

    iterate through nested dictionary (with iterkeys() method)
         and return with nested keys flattened into a tuple
    """
    if sys.hexversion < 0x03000000:
        keys = dictionary.iterkeys
        keystr = "iterkeys"
    else:
        keys = dictionary.keys
        keystr = "keys"
    for key in keys():
        value = dictionary[key]
        if hasattr(value, keystr):
            for keykey, value in flatten_nested_items(value):
                yield (key,) + keykey, value
        else:
            yield (key,), value 
Example #14
Source File: Utils.py    From 802.11ah-ns3 with GNU General Public License v2.0 6 votes vote down vote up
def writef_win32(f,data,m='w',encoding='ISO8859-1'):
	if sys.hexversion>0x3000000 and not'b'in m:
		data=data.encode(encoding)
		m+='b'
	flags=os.O_CREAT|os.O_TRUNC|os.O_WRONLY|os.O_NOINHERIT
	if'b'in m:
		flags|=os.O_BINARY
	if'+'in m:
		flags|=os.O_RDWR
	try:
		fd=os.open(f,flags)
	except OSError:
		raise IOError('Cannot write to %r'%f)
	f=os.fdopen(fd,m)
	try:
		f.write(data)
	finally:
		f.close() 
Example #15
Source File: test_checkpyver.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def test_patched_errwindow(capfd, mocker, monkeypatch):
    """Test with a patched sys.hexversion and a fake Tk."""
    monkeypatch.setattr(checkpyver.sys, 'hexversion', 0x03040000)
    monkeypatch.setattr(checkpyver.sys, 'exit', lambda status: None)

    try:
        import tkinter  # pylint: disable=unused-import
    except ImportError:
        tk_mock = mocker.patch('qutebrowser.misc.checkpyver.Tk',
                               spec=['withdraw'], new_callable=mocker.Mock)
        msgbox_mock = mocker.patch('qutebrowser.misc.checkpyver.messagebox',
                                   spec=['showerror'])
    else:
        tk_mock = mocker.patch('qutebrowser.misc.checkpyver.Tk', autospec=True)
        msgbox_mock = mocker.patch('qutebrowser.misc.checkpyver.messagebox',
                                   autospec=True)

    checkpyver.check_python_version()
    stdout, stderr = capfd.readouterr()
    assert not stdout
    assert not stderr
    tk_mock.assert_called_with()
    tk_mock().withdraw.assert_called_with()
    msgbox_mock.showerror.assert_called_with("qutebrowser: Fatal error!",
                                             unittest.mock.ANY) 
Example #16
Source File: Utils.py    From 802.11ah-ns3 with GNU General Public License v2.0 6 votes vote down vote up
def readf(fname,m='r',encoding='ISO8859-1'):
	if sys.hexversion>0x3000000 and not'b'in m:
		m+='b'
		f=open(fname,m)
		try:
			txt=f.read()
		finally:
			f.close()
		if encoding:
			txt=txt.decode(encoding)
		else:
			txt=txt.decode()
	else:
		f=open(fname,m)
		try:
			txt=f.read()
		finally:
			f.close()
	return txt 
Example #17
Source File: wfapi.py    From terraform-templates with Apache License 2.0 6 votes vote down vote up
def _certifi_ssl_context(self):
        if (sys.version_info.major == 2 and sys.hexversion >= 0x02070900 or
           sys.version_info.major == 3 and sys.hexversion >= 0x03040300):
            where = certifi.where()
            self._log(DEBUG1, 'certifi %s: %s', certifi.__version__, where)
            return ssl.create_default_context(
                purpose=ssl.Purpose.SERVER_AUTH,
                cafile=where)
        else:
            return None


#
# XXX USE OF cloud_ssl_context() IS DEPRECATED!
#
# If your operating system certificate store is out of date you can
# install certifi (https://pypi.python.org/pypi/certifi) and its CA
# bundle will be used for SSL server certificate verification when
# ssl_context is None.
# 
Example #18
Source File: Utils.py    From royal-chaos with MIT License 5 votes vote down vote up
def writef(fname,data,m='w',encoding='ISO8859-1'):
	if sys.hexversion>0x3000000 and not'b'in m:
		data=data.encode(encoding)
		m+='b'
	f=open(fname,m)
	try:
		f.write(data)
	finally:
		f.close() 
Example #19
Source File: Utils.py    From royal-chaos with MIT License 5 votes vote down vote up
def readf_win32(f,m='r',encoding='ISO8859-1'):
	flags=os.O_NOINHERIT|os.O_RDONLY
	if'b'in m:
		flags|=os.O_BINARY
	if'+'in m:
		flags|=os.O_RDWR
	try:
		fd=os.open(f,flags)
	except OSError:
		raise IOError('Cannot read from %r'%f)
	if sys.hexversion>0x3000000 and not'b'in m:
		m+='b'
		f=os.fdopen(fd,m)
		try:
			txt=f.read()
		finally:
			f.close()
		if encoding:
			txt=txt.decode(encoding)
		else:
			txt=txt.decode()
	else:
		f=os.fdopen(fd,m)
		try:
			txt=f.read()
		finally:
			f.close()
	return txt 
Example #20
Source File: pdfid.py    From sift-saltstack with MIT License 5 votes vote down vote up
def __init__(self, file):
        self.file = file
        if file == '':
            self.infile = sys.stdin
        elif file.lower().startswith('http://') or file.lower().startswith('https://'):
            try:
                if sys.hexversion >= 0x020601F0:
                    self.infile = urllib23.urlopen(file, timeout=5)
                else:
                    self.infile = urllib23.urlopen(file)
            except urllib23.HTTPError:
                print('Error accessing URL %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        elif file.lower().endswith('.zip'):
            try:
                self.zipfile = zipfile.ZipFile(file, 'r')
                self.infile = self.zipfile.open(self.zipfile.infolist()[0], 'r', C2BIP3('infected'))
            except:
                print('Error opening file %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        else:
            try:
                self.infile = open(file, 'rb')
            except:
                print('Error opening file %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        self.ungetted = [] 
Example #21
Source File: Utils.py    From royal-chaos with MIT License 5 votes vote down vote up
def h_cmd(ins):
	if isinstance(ins,str):
		ret=ins
	elif isinstance(ins,list)or isinstance(ins,tuple):
		ret=str([h_cmd(x)for x in ins])
	else:
		ret=str(h_fun(ins))
	if sys.hexversion>0x3000000:
		ret=ret.encode('iso8859-1','xmlcharrefreplace')
	return ret 
Example #22
Source File: pdf-parser.py    From CIRTKit with MIT License 5 votes vote down vote up
def __init__(self, file):
        self.file = file
        if file.lower().startswith('http://') or file.lower().startswith('https://'):
            try:
                if sys.hexversion >= 0x020601F0:
                    self.infile = urllib23.urlopen(file, timeout=5)
                else:
                    self.infile = urllib23.urlopen(file)
            except urllib23.HTTPError:
                print('Error accessing URL %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        elif file.lower().endswith('.zip'):
            try:
                self.zipfile = zipfile.ZipFile(file, 'r')
                self.infile = self.zipfile.open(self.zipfile.infolist()[0], 'r', C2BIP3('infected'))
            except:
                print('Error opening file %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        else:
            try:
                self.infile = open(file, 'rb')
            except:
                print('Error opening file %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        self.ungetted = []
        self.position = -1 
Example #23
Source File: pdf-parser.py    From sift-saltstack with MIT License 5 votes vote down vote up
def __init__(self, file):
        self.file = file
        if file.lower().startswith('http://') or file.lower().startswith('https://'):
            try:
                if sys.hexversion >= 0x020601F0:
                    self.infile = urllib23.urlopen(file, timeout=5)
                else:
                    self.infile = urllib23.urlopen(file)
            except urllib23.HTTPError:
                print('Error accessing URL %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        elif file.lower().endswith('.zip'):
            try:
                self.zipfile = zipfile.ZipFile(file, 'r')
                self.infile = self.zipfile.open(self.zipfile.infolist()[0], 'r', C2BIP3('infected'))
            except:
                print('Error opening file %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        else:
            try:
                self.infile = open(file, 'rb')
            except:
                print('Error opening file %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        self.ungetted = []
        self.position = -1 
Example #24
Source File: sslcompat.py    From Protect4 with GNU General Public License v3.0 5 votes vote down vote up
def _optional_dependencies():
    try:
        import ipaddress  # noqa
        logger.debug('ipaddress module is available')
        ipaddr = True
    except ImportError:
        logger.warn('ipaddress module is unavailable')
        ipaddr = False

    if sys.hexversion < 0x030500F0:
        try:
            from backports.ssl_match_hostname import match_hostname, __version__ as ver
            ver = list(map(int, ver.split('.')))
            logger.debug('backports.ssl_match_hostname module is available')
            match = match_hostname
            if ver[0] * 10 + ver[1] >= 35:
                return ipaddr, match
            else:
                logger.warn('backports.ssl_match_hostname module is too old')
                ipaddr = False
        except ImportError:
            logger.warn('backports.ssl_match_hostname is unavailable')
            ipaddr = False
    try:
        from ssl import match_hostname
        logger.debug('ssl.match_hostname is available')
        match = match_hostname
    except ImportError:
        logger.warn('using legacy validation callback')
        match = legacy_validate_callback
    return ipaddr, match 
Example #25
Source File: pdfid.py    From CIRTKit with MIT License 5 votes vote down vote up
def __init__(self, file):
        self.file = file
        if file == '':
            self.infile = sys.stdin
        elif file.lower().startswith('http://') or file.lower().startswith('https://'):
            try:
                if sys.hexversion >= 0x020601F0:
                    self.infile = urllib23.urlopen(file, timeout=5)
                else:
                    self.infile = urllib23.urlopen(file)
            except urllib23.HTTPError:
                print('Error accessing URL %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        elif file.lower().endswith('.zip'):
            try:
                self.zipfile = zipfile.ZipFile(file, 'r')
                self.infile = self.zipfile.open(self.zipfile.infolist()[0], 'r', C2BIP3('infected'))
            except:
                print('Error opening file %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        else:
            try:
                self.infile = open(file, 'rb')
            except:
                print('Error opening file %s' % file)
                print(sys.exc_info()[1])
                sys.exit()
        self.ungetted = [] 
Example #26
Source File: test_coverage_sorteddict.py    From pyFileFixity with MIT License 5 votes vote down vote up
def get_keysview(dic):
    if hexversion < 0x03000000:
        return dic.viewkeys()
    else:
        return dic.keys() 
Example #27
Source File: test_coverage_sorteddict.py    From pyFileFixity with MIT License 5 votes vote down vote up
def test_values_view_and():
    if hexversion < 0x02070000: raise TypeError
    mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
    temp = SortedDict(mapping)
    values = get_valuesview(temp)
    that = dict(mapping)
    that_values = get_valuesview(that)
    values & that_values 
Example #28
Source File: test_coverage_sorteddict.py    From pyFileFixity with MIT License 5 votes vote down vote up
def test_values_view_sub():
    if hexversion < 0x02070000: raise TypeError
    mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
    temp = SortedDict(mapping)
    values = get_valuesview(temp)
    that = dict(mapping)
    that_values = get_valuesview(that)
    values - that_values 
Example #29
Source File: test_coverage_sorteddict.py    From pyFileFixity with MIT License 5 votes vote down vote up
def test_values_view_or():
    if hexversion < 0x02070000: raise TypeError
    mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
    temp = SortedDict(mapping)
    values = get_valuesview(temp)
    that = dict(mapping)
    that_values = get_valuesview(that)
    values | that_values 
Example #30
Source File: test_coverage_sorteddict.py    From pyFileFixity with MIT License 5 votes vote down vote up
def test_values_view_xor():
    if hexversion < 0x02070000: raise TypeError
    mapping = [(val, pos) for pos, val in enumerate(string.ascii_lowercase)]
    temp = SortedDict(mapping)
    values = get_valuesview(temp)
    that = dict(mapping)
    that_values = get_valuesview(that)
    values ^ that_values