Python sys.version_info() Examples

The following are 30 code examples for showing how to use sys.version_info(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module sys , or try the search function .

Example 1
def isUpdatesAvailable(cls, path):
        if sys.version_info < (3, 0):
            return False
        # pylint: disable=broad-except
        if not os.path.isfile(os.path.join(path, "files.xml")):
            return True
        try:
            available = dict()
            for it in ET.parse(os.path.join(path, "files.xml")).iter():
                if it.tag == "File":
                    available[it.text] = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")

            path = NamedTemporaryFile()
            path.close()
            urllib.request.urlretrieve("https://www.gurux.fi/obis/files.xml", path.name)
            for it in ET.parse(path.name).iter():
                if it.tag == "File":
                    tmp = datetime.datetime.strptime(it.attrib["Modified"], "%d-%m-%Y")
                    if not it.text in available or available[it.text] != tmp:
                        return True
        except Exception as e:
            print(e)
            return True
        return False 
Example 2
def updateManufactureSettings(cls, directory):
        #
        # Update manufacturer settings from the Gurux www server.
        #
        # directory: Target directory.
        #
        if sys.version_info >= (3, 0):
            return
        if not os.path.isdir(directory):
            os.mkdir(directory)
            if not os.path.isdir(directory):
                return
        path = os.path.join(directory, "files.xml")
        urllib.request.urlretrieve("https://www.gurux.fi/obis/files.xml", path)
        for it in ET.parse(path).iter():
            if it.tag == "File":
                path = os.path.join(directory, it.text)
                urllib.request.urlretrieve("https://www.gurux.fi/obis/" + it.text, path) 
Example 3
Project: Gurux.DLMS.Python   Author: Gurux   File: GXByteBuffer.py    License: GNU General Public License v2.0 6 votes vote down vote up
def hex(cls, value, addSpace=True, index=0, count=None):
        """
        Convert byte array to hex string.
        """
        #Return empty string if array is empty.
        if not value:
            return ""
        hexChars = ""
        #Python 2.7 handles bytes as a string array. It's changed to bytearray.
        if sys.version_info < (3, 0) and not isinstance(value, bytearray):
            value = bytearray(value)
        if count is None:
            count = len(value)
        for it in value[index:count]:
            hexChars += GXByteBuffer.__HEX_ARRAY[it >> GXByteBuffer.__NIBBLE]
            hexChars += GXByteBuffer.__HEX_ARRAY[it & GXByteBuffer.__LOW_BYTE_PART]
            if addSpace:
                hexChars += ' '
        return hexChars.strip() 
Example 4
Project: mutatest   Author: EvanKepner   File: conftest.py    License: MIT License 6 votes vote down vote up
def write_cov_file(line_data: Dict[str, List[int]], fname: str) -> None:
    """Write a coverage file supporting both Coverage v4 and v5.

    Args:
        line_data: Dictionary of line data for the coverage file.
        fname: string filename for output location (absolute path)

    Returns:
        None
    """
    if coverage.version_info[0] == 4:
        covdata = coverage.CoverageData()
        covdata.add_lines(line_data)
        covdata.write_file(fname)

    else:
        # assume coverage v 5
        covdata = coverage.CoverageData(basename=fname)
        covdata.add_lines(line_data)
        covdata.write()


####################################################################################################
# CLI: MOCK ARGS
#################################################################################################### 
Example 5
Project: cherrypy   Author: cherrypy   File: profiler.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def stats(self, filename, sortby='cumulative'):
        """:rtype stats(index): output of print_stats() for the given profile.
        """
        sio = io.StringIO()
        if sys.version_info >= (2, 5):
            s = pstats.Stats(os.path.join(self.path, filename), stream=sio)
            s.strip_dirs()
            s.sort_stats(sortby)
            s.print_stats()
        else:
            # pstats.Stats before Python 2.5 didn't take a 'stream' arg,
            # but just printed to stdout. So re-route stdout.
            s = pstats.Stats(os.path.join(self.path, filename))
            s.strip_dirs()
            s.sort_stats(sortby)
            oldout = sys.stdout
            try:
                sys.stdout = sio
                s.print_stats()
            finally:
                sys.stdout = oldout
        response = sio.getvalue()
        sio.close()
        return response 
Example 6
Project: cherrypy   Author: cherrypy   File: reprconf.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def build_Call(self, o):
        if sys.version_info >= (3, 5):
            return self._build_call35(o)

        callee = self.build(o.func)

        if o.args is None:
            args = ()
        else:
            args = tuple([self.build(a) for a in o.args])

        if o.starargs is None:
            starargs = ()
        else:
            starargs = tuple(self.build(o.starargs))

        if o.kwargs is None:
            kwargs = {}
        else:
            kwargs = self.build(o.kwargs)
        if o.keywords is not None:  # direct a=b keywords
            for kw in o.keywords:
                # preference because is a direct keyword against **kwargs
                kwargs[kw.arg] = self.build(kw.value)
        return callee(*(args + starargs), **kwargs) 
Example 7
Project: cherrypy   Author: cherrypy   File: test_params.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_syntax(self):
        if sys.version_info < (3,):
            return self.skip('skipped (Python 3 only)')
        code = textwrap.dedent("""
            class Root:
                @cherrypy.expose
                @cherrypy.tools.params()
                def resource(self, limit: int):
                    return type(limit).__name__
            conf = {'/': {'tools.params.on': True}}
            cherrypy.tree.mount(Root(), config=conf)
            """)
        exec(code)

        self.getPage('/resource?limit=0')
        self.assertStatus(200)
        self.assertBody('int') 
Example 8
Project: sump2   Author: blackmesalabs   File: bd_server.py    License: GNU General Public License v3.0 6 votes vote down vote up
def wr( self, str ):
    if ( self.debug ):
      print("FT600_WR:" +  str );
    str = "~".join( str );# only using 8bits of 16bit FT600, so pad with ~
    bytes_to_write = len( str );# str is now "~1~2~3 .. ~e~f" - Twice as long
    channel = 0;
    result = False;
    timeout = 5;
    tx_pipe = 0x02 + channel;
    if sys.platform == 'linux2':
      tx_pipe -= 0x02;
    if ( sys.version_info.major == 3 ):
      str = str.encode('latin1');
    xferd = 0
    while ( xferd != bytes_to_write ):
      # write data to specified pipe
      xferd += self.D3XX.writePipe(tx_pipe,str,bytes_to_write-xferd);
    return; 
Example 9
Project: twstock   Author: mlouielu   File: realtime.py    License: MIT License 6 votes vote down vote up
def get_raw(stocks) -> dict:
    req = requests.Session()
    req.get(SESSION_URL, proxies=get_proxies())

    r = req.get(
        STOCKINFO_URL.format(
            stock_id=_join_stock_id(stocks),
            time=int(time.time()) * 1000))

    if sys.version_info < (3, 5):
        try:
            return r.json()
        except ValueError:
            return {'rtmessage': 'json decode error', 'rtcode': '5000'}
    else:
        try:
            return r.json()
        except json.decoder.JSONDecodeError:
            return {'rtmessage': 'json decode error', 'rtcode': '5000'} 
Example 10
def test_recordio():
    frec = tempfile.mktemp()
    N = 255

    writer = mx.recordio.MXRecordIO(frec, 'w')
    for i in range(N):
        if sys.version_info[0] < 3:
            writer.write(str(chr(i)))
        else:
            writer.write(bytes(str(chr(i)), 'utf-8'))
    del writer

    reader = mx.recordio.MXRecordIO(frec, 'r')
    for i in range(N):
        res = reader.read()
        if sys.version_info[0] < 3:
            assert res == str(chr(i))
        else:
            assert res == bytes(str(chr(i)), 'utf-8') 
Example 11
def test_indexed_recordio():
    fidx = tempfile.mktemp()
    frec = tempfile.mktemp()
    N = 255

    writer = mx.recordio.MXIndexedRecordIO(fidx, frec, 'w')
    for i in range(N):
        if sys.version_info[0] < 3:
            writer.write_idx(i, str(chr(i)))
        else:
            writer.write_idx(i, bytes(str(chr(i)), 'utf-8'))
    del writer

    reader = mx.recordio.MXIndexedRecordIO(fidx, frec, 'r')
    keys = reader.keys
    assert sorted(keys) == [i for i in range(N)]
    random.shuffle(keys)
    for i in keys:
        res = reader.read_idx(i)
        if sys.version_info[0] < 3:
            assert res == str(chr(i))
        else:
            assert res == bytes(str(chr(i)), 'utf-8') 
Example 12
def test_kernel_error_checking():
    # Running tests that may throw exceptions out of worker threads will stop CI testing
    # if not run in a separate process (with its own address space for CUDA compatibility).
    try:
        mpctx = mp.get_context('spawn')
    except:
        print('SKIP: python%s.%s lacks the required process fork-exec support ... ' %
              sys.version_info[0:2], file=sys.stderr, end='')
    else:
        with discard_stderr():
            for f in [kernel_error_check_imperative, kernel_error_check_symbolic]:
                p = mpctx.Process(target=f)
                p.start()
                p.join()
                assert p.exitcode != 0,\
                    "Expected a synchronous kernel error from %s(), none seen." % f.__name__ 
Example 13
Project: Recipes   Author: Lasagne   File: cifar10.py    License: MIT License 6 votes vote down vote up
def download_dataset(path, source='https://www.cs.toronto.edu/~kriz/'
                                  'cifar-10-python.tar.gz'):
    """
    Downloads and extracts the dataset, if needed.
    """
    files = ['data_batch_%d' % (i + 1) for i in range(5)] + ['test_batch']
    for fn in files:
        if not os.path.exists(os.path.join(path, 'cifar-10-batches-py', fn)):
            break  # at least one file is missing
    else:
        return  # dataset is already complete

    print("Downloading and extracting %s into %s..." % (source, path))
    if sys.version_info[0] == 2:
        from urllib import urlopen
    else:
        from urllib.request import urlopen
    import tarfile
    if not os.path.exists(path):
        os.makedirs(path)
    u = urlopen(source)
    with tarfile.open(fileobj=u, mode='r|gz') as f:
        f.extractall(path=path)
    u.close() 
Example 14
Project: django-payfast   Author: PiDelport   File: forms.py    License: MIT License 6 votes vote down vote up
def is_payfast_ip_address(ip_address_str):
    """
    Return True if ip_address_str matches one of PayFast's server IP addresses.

    Setting: `PAYFAST_IP_ADDRESSES`

    :type ip_address_str: str
    :rtype: bool
    """
    # TODO: Django system check for validity?
    payfast_ip_addresses = getattr(settings, 'PAYFAST_IP_ADDRESSES',
                                   conf.DEFAULT_PAYFAST_IP_ADDRESSES)

    if sys.version_info < (3,):
        # Python 2 usability: Coerce str to unicode, to avoid very common TypeErrors.
        # (On Python 3, this should generally not happen:
        #  let unexpected bytes values fail as expected.)
        ip_address_str = unicode(ip_address_str)  # noqa: F821
        payfast_ip_addresses = [unicode(address) for address in payfast_ip_addresses]  # noqa: F821

    return any(ip_address(ip_address_str) in ip_network(payfast_address)
               for payfast_address in payfast_ip_addresses) 
Example 15
Project: django-payfast   Author: PiDelport   File: api.py    License: MIT License 6 votes vote down vote up
def _prepare_signable_fields(
        valid_field_order,  # type: Sequence[str]
        data_fields,  # type: Mapping[str, str]
):  # type: (...) -> SignableFields
    """
    Prepare PayFast submission variables for signing, using the given field order.

    :raise ValueError:
        If `data_fields` contains any unexpected field names not in `valid_field_order`.
    """
    present_fields = (set(data_fields.keys()) if sys.version_info < (3,) else
                      data_fields.keys())
    extra_fields = present_fields - set(valid_field_order)
    if extra_fields:
        raise ValueError('Data contains unexpected fields: {!r}'.format(extra_fields))

    return [
        (name, data_fields[name]) for name in valid_field_order
        if name in data_fields
    ] 
Example 16
Project: mutatest   Author: EvanKepner   File: transformers.py    License: MIT License 5 votes vote down vote up
def end_col_offset(self) -> Optional[int]:
        """End col offset: Python 3.8 will have this defined, in Python 3.7 it will be None."""
        ecol: Optional[int] = getattr(self.node, "end_col_offset", None)
        return ecol


####################################################################################################
# MUTATE AST Definitions
# Includes MutateBase and Mixins for 3.7 and 3.8 AST support
# MutateAST is constructed from Base + Mixins depending on sys.version_info
#################################################################################################### 
Example 17
Project: mutatest   Author: EvanKepner   File: test_api.py    License: MIT License 5 votes vote down vote up
def test_create_mutant_with_cache(binop_file, stdoutIO):
    """Change ast.Add to ast.Mult in a mutation including pycache changes."""
    genome = Genome(source_file=binop_file)

    # this target is the add_five() function, changing add to mult
    end_lineno = None if sys.version_info < (3, 8) else 10
    end_col_offset = None if sys.version_info < (3, 8) else 16

    target_idx = LocIndex(
        ast_class="BinOp",
        lineno=10,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    )
    mutation_op = ast.Mult

    mutant = genome.mutate(target_idx, mutation_op, write_cache=True)

    # uses the redirection for stdout to capture the value from the final output of binop_file
    with stdoutIO() as s:
        exec(mutant.mutant_code)
        assert int(s.getvalue()) == 25

    tag = sys.implementation.cache_tag
    expected_cfile = binop_file.parent / "__pycache__" / ".".join([binop_file.stem, tag, "pyc"])

    assert mutant.src_file == binop_file
    assert mutant.cfile == expected_cfile
    assert mutant.src_idx == target_idx 
Example 18
Project: mutatest   Author: EvanKepner   File: conftest.py    License: MIT License 5 votes vote down vote up
def boolop_expected_loc():
    """Expected location index of the boolop fixture"""
    # Py 3.7 vs 3.8
    end_lineno = None if sys.version_info < (3, 8) else 2
    end_col_offset = None if sys.version_info < (3, 8) else 18
    return LocIndex(
        ast_class="BoolOp",
        lineno=2,
        col_offset=11,
        op_type=ast.And,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    ) 
Example 19
Project: mutatest   Author: EvanKepner   File: test_transformers.py    License: MIT License 5 votes vote down vote up
def test_MutateAST_visit_binop_37(binop_file):
    """Read only test to ensure locations are aggregated."""
    tree = Genome(binop_file).ast

    # Py 3.7 vs. Py 3.8
    end_lineno = None if sys.version_info < (3, 8) else 6
    end_col_offset = None if sys.version_info < (3, 8) else 17

    test_idx = LocIndex(
        ast_class="BinOp",
        lineno=6,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    )
    test_mutation = ast.Pow

    # apply the mutation to the original tree copy
    testing_tree = deepcopy(tree)
    mutated_tree = MutateAST(target_idx=test_idx, mutation=test_mutation).visit(testing_tree)

    # revisit in read-only mode to gather the locations of the new nodes
    mast = MutateAST(readonly=True)
    mast.visit(mutated_tree)

    # four locations from the binary operations in binop_file
    assert len(mast.locs) == 4

    # locs is an unordered set, cycle through to thd target and check the mutation
    for loc in mast.locs:
        if (
            loc.lineno == 6
            and loc.col_offset == 11
            and loc.end_lineno == end_lineno
            and loc.end_col_offset == end_col_offset
        ):
            assert loc.op_type == test_mutation 
Example 20
Project: mutatest   Author: EvanKepner   File: test_run.py    License: MIT License 5 votes vote down vote up
def binop_Add_LocIdx():
    """Binop Add LocIdx as a target for mutations."""
    end_lineno = None if sys.version_info < (3, 8) else 10
    end_col_offset = None if sys.version_info < (3, 8) else 16
    return LocIndex(
        ast_class="BinOp",
        lineno=10,
        col_offset=11,
        op_type=ast.Add,
        end_lineno=end_lineno,
        end_col_offset=end_col_offset,
    ) 
Example 21
Project: mutatest   Author: EvanKepner   File: test_run.py    License: MIT License 5 votes vote down vote up
def test_run_mutation_trials_bad_binop(
    bos, bod, exp_trials, parallel, single_binop_file_with_bad_test, change_to_tmp
):
    """Slow test to run detection trials on a simple mutation on a binop.

    Based on fixture, there is one Add operation, with 6 substitutions e.g.
    sub, div, mult, pow, mod, floordiv, therefore, 6 total trials are expected for a full run
    and 1 trial is expected when break on detected is used.

    Args:
        bos: break on survival
        bod: break on detection
        exp_trials: number of expected trials
        single_binop_file_with_good_test: fixture for single op with a good test
    """
    if sys.version_info < (3, 8) and parallel:
        pytest.skip("Under version 3.8 will not run parallel tests.")

    test_cmds = f"pytest {single_binop_file_with_bad_test.test_file.resolve()}".split()

    config = Config(
        n_locations=100, break_on_survival=bos, break_on_detected=bod, multi_processing=parallel
    )

    results_summary = run.run_mutation_trials(
        single_binop_file_with_bad_test.src_file.resolve(), test_cmds=test_cmds, config=config
    )

    assert len(results_summary.results) == exp_trials

    # in all trials the status should be survivors
    for mutant_trial in results_summary.results:
        assert mutant_trial.return_code == 0
        assert mutant_trial.status == "SURVIVED" 
Example 22
Project: vergeml   Author: mme   File: libraries.py    License: MIT License 5 votes vote down vote up
def version():
        return ".".join(map(str, sys.version_info[:3])) 
Example 23
Project: aospy   Author: spencerahill   File: versioneer.py    License: Apache License 2.0 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example 24
Project: aospy   Author: spencerahill   File: _version.py    License: Apache License 2.0 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example 25
Project: wechatpy   Author: wechatpy   File: conftest.py    License: MIT License 5 votes vote down vote up
def pytest_ignore_collect(path, config):
    if "asyncio" in str(path):
        if sys.version_info < (3, 4, 0):
            return True 
Example 26
Project: xrft   Author: xgcm   File: versioneer.py    License: MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example 27
Project: xrft   Author: xgcm   File: _version.py    License: MIT License 5 votes vote down vote up
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,
                env=None):
    """Call the given command(s)."""
    assert isinstance(commands, list)
    p = None
    for c in commands:
        try:
            dispcmd = str([c] + args)
            # remember shell=False, so use git.cmd on windows, not just git
            p = subprocess.Popen([c] + args, cwd=cwd, env=env,
                                 stdout=subprocess.PIPE,
                                 stderr=(subprocess.PIPE if hide_stderr
                                         else None))
            break
        except EnvironmentError:
            e = sys.exc_info()[1]
            if e.errno == errno.ENOENT:
                continue
            if verbose:
                print("unable to run %s" % dispcmd)
                print(e)
            return None, None
    else:
        if verbose:
            print("unable to find command, tried %s" % (commands,))
        return None, None
    stdout = p.communicate()[0].strip()
    if sys.version_info[0] >= 3:
        stdout = stdout.decode()
    if p.returncode != 0:
        if verbose:
            print("unable to run %s (error)" % dispcmd)
            print("stdout was %s" % stdout)
        return None, p.returncode
    return stdout, p.returncode 
Example 28
Project: cherrypy   Author: cherrypy   File: cpstats.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _get_threading_ident():
    if sys.version_info >= (3, 3):
        return threading.get_ident()
    return threading._get_ident() 
Example 29
Project: cherrypy   Author: cherrypy   File: test_tools.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testToolWithConfig(self):
        if not sys.version_info >= (2, 5):
            return self.skip('skipped (Python 2.5+ only)')

        self.getPage('/tooldecs/blah')
        self.assertHeader('Content-Type', 'application/data') 
Example 30
Project: cherrypy   Author: cherrypy   File: test_objectmapping.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testKeywords(self):
        if sys.version_info < (3,):
            return self.skip('skipped (Python 3 only)')
        exec("""class Root(object):
    @cherrypy.expose
    def hello(self, *, name='world'):
        return 'Hello %s!' % name
cherrypy.tree.mount(Application(Root(), '/keywords'))""")

        self.getPage('/keywords/hello')
        self.assertStatus(200)
        self.getPage('/keywords/hello/extra')
        self.assertStatus(404)