sys.version_info.major

Here are the examples of the python api sys.version_info.major taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: OpenNFB
Source File: launcher.py
View license
def to_python(obj):
	if isinstance(obj, str):
		return str(obj)
	elif sys.version_info.major < 3:
		if isinstance(obj, unicode):
			return str(obj)
	if isinstance(obj, int):
		return obj
	# Ugly Hack: If index 1 exists, we heuristically assume the table was a list/tuple once
	elif 1 in obj:
		return [to_python(item) for item in obj.values()]
	# Assume dict table
	else:
		return {str(key): to_python(obj[key]) for key in obj}

Example 2

Project: python2-trepan
Source File: cmdfns.py
View license
def deparse_fn(code):
    try:
        from uncompyle6.semantics.pysource import deparse_code
    except ImportError:
        return None
    sys_version = sys.version_info.major + (sys.version_info.minor / 10.0)
    try:
        out = io.StringIO()
        deparsed = deparse_code(sys_version, code, out)
        return deparsed.text
    except:
        raise
    return None

Example 3

Project: BitXBay
Source File: openssl.py
View license
    def malloc(self, data, size):
        """
        returns a create_string_buffer (ctypes)
        """
        buffer = None
        if data != 0:
            if sys.version_info.major == 3 and isinstance(data, type('')):
                data = data.encode()
            buffer = self.create_string_buffer(data, size)
        else:
            buffer = self.create_string_buffer(size)
        return buffer

Example 4

Project: cinspect
Source File: download.py
View license
def _prompt_overwrite(path):
    if sys.version_info.major > 2:
        ask = input
    else:
        ask = raw_input
    answer = ask('%s exists. Overwrite? [y/N] ' % path)
    return True if answer.strip().lower()[:1] == 'y' else False

Example 5

Project: asyncio
Source File: release.py
View license
    @staticmethod
    def running():
        bits = get_architecture_bits()
        pyver = PythonVersion(sys.version_info.major,
                              sys.version_info.minor,
                              bits)
        pyver._executable = sys.executable
        return pyver

Example 6

Project: asyncoro
Source File: webserver.py
View license
def process(conn, coro=None):
    msg = "HTTP/1.0 200 OK\r\nContent-Length: 5\r\n\r\nPong!\r\n"
    if sys.version_info.major >= 3:
        msg = bytes(msg, 'ascii')
    yield conn.sendall(msg)
    conn.close()

Example 7

Project: BGmi
Source File: models.py
View license
    def _unicodeize(self):
        for i in self.fields:
            v = self.__dict__.get(i, '')
            if isinstance(v, str):
                if sys.version_info.major < 3:
                    v = unicode(v.decode('utf-8'))
                else:
                    v = str(v)
                self.__dict__[i] = v

Example 8

Project: PyCIRCLean
Source File: test.py
View license
    def test_filecheck_2(self):
        if sys.version_info.major >= 3:
            return
        src = os.path.join(self.curpath, 'tests/src2')
        dst = os.path.join(self.curpath, 'tests/dst')
        spec = KittenGroomerFileCheck(src, dst, debug=True)
        spec.processdir()
        self.dump_logs(spec)

Example 9

Project: db_file_storage
Source File: form_widgets.py
View license
def db_file_widget(cls):
    """Edit the download-link inner text."""
    def get_template_substitution_values(self, value):
        subst = super(cls, self).get_template_substitution_values(value)
        unquoted = unquote(value.url.split('%2F')[-1])
        if sys.version_info.major == 2:  # python 2
            from django.utils.encoding import force_unicode
            unquoted = force_unicode(unquoted)
        subst['initial'] = escape(unquoted)
        return subst
    setattr(
        cls,
        'get_template_substitution_values',
        get_template_substitution_values
    )
    return cls

Example 10

Project: slacksocket
Source File: models.py
View license
    def _get_mentions(self, text):
        mentions = re.findall('<@\w+>', text)

        if mentions and sys.version_info.major == 2:
            return [ unicode(m).translate(translate_map) for m in mentions ]

        if mentions and sys.version_info.major == 3:
            return [ str(m).translate(translate_map) for m in mentions ]

        return []

Example 11

Project: quokka
Source File: test_model.py
View license
def eval_b(x):
    """Evaluate if to encode the value is necessary.
    """
    if sys.version_info.major == 2:
        return x
    else:
        import codecs
        return codecs.utf_8_encode(x)[0]

Example 12

Project: haxor
Source File: __init__.py
View license
    def __repr__(self):
        retval = '<hackernews.Item: {0} - {1}>'.format(
            self.item_id, self.title)
        if sys.version_info.major < 3:
            return retval.encode('utf-8', errors='backslashreplace')
        return retval

Example 13

Project: quark
Source File: quark_runtime.py
View license
def _println(obj):
    if obj is None:
        message = u"null\n"
    else:
        message = u"%s\n" % (obj,)
    if sys.version_info.major == 2:
        message = message.encode("utf8")
    sys.stdout.write(message)
    sys.stdout.flush()

Example 14

View license
    def NOT_WORKING_test_tty(self):
        # FIXME: Mocking 'file' is not trivial... and fails for now
        from sys import version_info
        if version_info.major == 2:
            import __builtin__ as builtins  # pylint:disable=import-error
        else:
            import builtins  # pylint:disable=import-error

        with patch.object(builtins, 'open', mock_open(), create=True):
            with open('foo', 'w+') as handle:
                cloudpickle.dumps(handle)

Example 15

Project: Subspace
Source File: openssl.py
View license
    def malloc(self, data, size):
        """
        returns a create_string_buffer (ctypes)
        """
        buffer = None
        if data != 0:
            if sys.version_info.major == 3 and isinstance(data, type('')):
                data = data.encode()
            buffer = self.create_string_buffer(data, size)
        else:
            buffer = self.create_string_buffer(size)
        return buffer

Example 16

Project: pytaglib
Source File: test_bytes_unicode.py
View license
    def test_unicode_filename(self):
        """Ensure file can be opened if filename is provided as bytes object."""
        with copyTestFile('testöü.flac') as f:
            if sys.version_info.major == 2:
                f = unicode(f)
            tf = taglib.File(f)
            tf.close()

Example 17

Project: blueman
Source File: Base.py
View license
    def _init(self, interface_name, obj_path, *args, **kwargs):
        super(Base, self).__init__(
            g_name=self.__name,
            g_interface_name=interface_name,
            g_object_path=obj_path,
            g_bus_type=self.__bus_type,
            g_flags=Gio.DBusProxyFlags.NONE,
            *args, **kwargs)

        self.init()
        self.__interface_name = interface_name
        self.__fallback = {'Icon': 'blueman', 'Class': 0}

        if sys.version_info.major < 3:
            self.__variant_map = {str: 's', unicode: 's', int: 'u', bool: 'b'}
        else:
            self.__variant_map = {str: 's', int: 'u', bool: 'b'}

Example 18

Project: homebrew-pypi-poet
Source File: poet.py
View license
def formula_for(package):
    nodes = make_graph(package)
    resources = [value for key, value in nodes.items()
                 if key.lower() != package.lower()]

    if package in nodes:
        root = nodes[package]
    elif package.lower() in nodes:
        root = nodes[package.lower()]
    else:
        raise Exception("Could not find package {} in nodes {}".format(package, nodes.keys()))

    python = "python" if sys.version_info.major == 2 else "python3"
    return FORMULA_TEMPLATE.render(package=root,
                                   resources=resources,
                                   python=python,
                                   ResourceTemplate=RESOURCE_TEMPLATE)

Example 19

Project: qibuild
Source File: test_qipy_pip.py
View license
def test_simple(qipy_action, args):
    qipy_action("bootstrap", "--no-site-packages")
    python_worktree = qipy.parsers.get_python_worktree(args)
    venv_path = python_worktree.venv_path
    version = "%s.%s" % (sys.version_info.major, sys.version_info.minor)
    parts = [venv_path, "lib", "site-packages", "tabulate.py"]
    if os.name != "nt":
        parts.insert(2, "python" + version)
    tabulate_path = os.path.join(*parts)
    assert not os.path.exists(tabulate_path)
    qipy_action("pip", "install", "tabulate")
    assert os.path.exists(tabulate_path)

Example 20

Project: try
Source File: __main__.py
View license
def normalize_python_version(ctx, param, value):  # pylint: disable=unused-argument
    """Normalize given python version."""
    if value is None:
        return "python{major}.{minor}".format(
            major=sys.version_info.major,
            minor=sys.version_info.minor)

    if re.match(r"\d\.\d", value):
        return "python{0}".format(value)

    return value

Example 21

Project: uberwriter
Source File: spellcheck.py
View license
        def __init__(self, *args, **kwargs):
            if sys.version_info.major == 3:
                super().__init__(*args, **kwargs)
            else:
                _list.__init__(self, *args, **kwargs)
            self.mapping = dict(self)

Example 22

Project: twitter-python-ads-sdk
Source File: http.py
View license
    def __user_agent(self):
        python_verison = "{0}.{1}".format(sys.version_info.major, sys.version_info.minor)
        return 'twitter-ads version: {0} platform: Python {1} ({2}/{3})'.format(
            get_version(),
            python_verison,
            platform.python_implementation(),
            sys.platform)

Example 23

Project: pyelliptic
Source File: openssl.py
View license
    def malloc(self, data, size):
        """
        returns a create_string_buffer (ctypes)
        """
        buffer = None
        if data != 0:
            if sys.version_info.major == 3 and isinstance(data, type('')):
                data = data.encode()
            buffer = self.create_string_buffer(data, size)
        else:
            buffer = self.create_string_buffer(size)
        return buffer

Example 24

Project: catkin
Source File: parse_package_xml.py
View license
def main(argv=sys.argv[1:]):
    """
    Reads given package_xml and writes extracted variables to outfile.
    """
    parser = argparse.ArgumentParser(description="Read package.xml and write extracted variables to stdout")
    parser.add_argument('package_xml')
    parser.add_argument('outfile')
    args = parser.parse_args(argv)
    package = parse_package(args.package_xml)

    # Force utf8 encoding for python3.
    # This way unicode files can still be processed on non-unicode locales.
    kwargs = {}
    if sys.version_info.major >= 3:
        kwargs['encoding'] = 'utf8'

    lines = _get_output(package)
    with open(args.outfile, 'w', **kwargs) as ofile:
        ofile.write('\n'.join(lines))

Example 25

Project: asyncoro
Source File: tut_sock_server.py
View license
def process(conn, coro=None):
    global n
    if sys.version_info.major >= 3:
        eol = ord('/')
    else:
        eol = '/'
    data = ''.encode()
    while True:
        data += yield conn.recv(128)
        if data[-1] == eol:
            break
    conn.close()
    n += 1
    print('recieved: %s' % data)

Example 26

Project: lymph
Source File: monkey.py
View license
def patch():
    if patch._initialized:
        return
    patch._initialized = True

    import gevent.monkey
    gevent.monkey.patch_all()

    import sys
    if sys.version_info.major < 3:
        _py2_patches()

    _export()

Example 27

Project: zipline
Source File: test_assets.py
View license
    def test_type_mismatch(self):
        if sys.version_info.major < 3:
            self.assertIsNotNone(self.asset3 < 'a')
            self.assertIsNotNone('a' < self.asset3)
        else:
            with self.assertRaises(TypeError):
                self.asset3 < 'a'
            with self.assertRaises(TypeError):
                'a' < self.asset3

Example 28

Project: knowledge-repo
Source File: render.py
View license
def render_post_raw(post):
    if isinstance(post, KnowledgePost):
        raw_post = post.read().encode('ascii', 'ignore')
    else:
        raw_post = post.text.encode('ascii', 'ignore')

    # NOTE: `str.encode()` returns a `bytes` object in Python 3
    if sys.version_info.major >= 3:
        return raw_post.decode('ascii', 'ignore')
    return raw_post

Example 29

Project: pims
Source File: test_common.py
View license
    def test_metadata(self):
        m = self.v.metadata
        with open(os.path.join(path, 'spestack_test_metadata.pkl'), 'rb') as p:
            if sys.version_info.major < 3:
                d = pickle.load(p)
            else:
                d = pickle.load(p, encoding="latin1")
                #spare4 is actually a byte array
                d["spare4"] = d["spare4"].encode("latin1")

        assert_equal(m, d)

Example 30

Project: py-sdm
Source File: features.py
View license
    def _get_dtype(self, categories, names, extras):
        dt = [
            ('features', object),
            ('category', categories.dtype),
            ('name', names.dtype)
        ]
        # in python 2 only, have to encode the names...sigh.
        if sys.version_info.major == 2:
            dt += [(n.encode(), 'O' if vals.ndim > 1 else vals.dtype)
                   for n, vals in iteritems(extras)]
        else:
            dt += [(n, 'O' if vals.ndim > 1 else vals.dtype)
                   for n, vals in iteritems(extras)]
        return dt

Example 31

Project: cytoplasm
Source File: defaults.py
View license
@Interpreter("mako")
@SaveReturned
def mako_interpreter(file, **kwargs):
    # pass kwargs to the mako template
    page = mako.template.Template(file.read(), lookup=mako_lookup,
            input_encoding='utf-8')
    # this is dumb but it's the only way I can make it work.
    if sys.version_info.major == 2:
        # if it's python 2, use .encode('utf-8', 'replace')
        return page.render_unicode(**kwargs).encode('utf-8', 'replace')
    elif sys.version_info.major == 3:
        # otherwise, just render it...
        return page.render_unicode(**kwargs)

Example 32

Project: pcs
Source File: qdevice.py
View license
def qdevice_sign_net_cert_request_cmd(lib, argv, modifiers):
    certificate_request = _read_stdin()
    signed = lib.qdevice.sign_net_cert_request(
        certificate_request,
        modifiers["name"]
    )
    if sys.version_info.major > 2:
        # In python3 base64.b64encode returns bytes.
        # In python2 base64.b64encode returns string.
        # Bytes is printed like this: b'bytes content'
        # and we need to get rid of that b'', so we change bytes to string.
        # Since it's base64encoded, it's safe to use ascii.
        signed = signed.decode("ascii")
    print(signed)

Example 33

Project: cinspect
Source File: test_hello_module.py
View license
    @classmethod
    def setUpClass(cls):
        cls.hello_dir = join(dirname(abspath(__file__)), 'data')
        cls.temp_dir = tempfile.mktemp()
        cls.index_path = join(cls.temp_dir, 'DB')
        cls._build_hello_module()
        cls._add_hello_to_path()

        if sys.version_info.major == 2:
            cls._setup_py_2()

Example 34

Project: genius
Source File: setup.py
View license
def read_text(file_path):
    """
    fix the default operating system encoding is not utf8.
    """
    if sys.version_info.major < 3:
        with open(file_path) as f:
            return f.read()
    with open(file_path, encoding="utf8") as f:
        return f.read()

Example 35

Project: meza
Source File: _compat.py
View license
def get_native_str(text):
    """Encode py2-unicode into bytes (py2-str) but leave py3 text as is
    """
    # dtype bug https://github.com/numpy/numpy/issues/2407
    if sys.version_info.major < 3:
        try:
            encoded = text.encode('ascii')
        except AttributeError:
            encoded = text
    else:
        encoded = text

    return encoded

Example 36

Project: badwolf
Source File: __init__.py
View license
    @property
    def python_name(self):
        python_version = int(self.options.get('python_version', sys.version_info.major))
        if python_version not in (2, 3):
            python_version = sys.version_info.major

        return 'python{}'.format(python_version)

Example 37

Project: MaTiSSe
Source File: create.py
View license
def create():
  """Function for creating tests reference values."""
  pyver = str(sys.version_info.major) + '.' + str(sys.version_info.minor) + '.' + str(sys.version_info.micro)
  print('Python' + pyver)
  for mdf in __md_files__:
    directory = os.path.dirname(mdf)
    inputfile = os.path.basename(mdf)
    print('Creating ' + directory)
    cmd = 'cd ' + directory + ' ; MaTiSSe.py -i ' + inputfile + ' -o ' + inputfile[:-3] + pyver + ' ; cd -'
    syswork(cmd)
  return

Example 38

Project: natto-py
Source File: test_support.py
View license
    def test_splitter_re(self):
        '''Test behavior of splitter support for MeCab boundary constraint parsing.

           Python 2: when using a compiled re w/out re.U, only 1 hit
           Python 3: when using a compiled re w/out re.U, all 2 hits
        '''
        ver = sys.version_info.major
        key = "py{}".format(ver)

        yml = self.yaml.get('text7')
        text = self._u2str(yml.get('text'))
        pat1 = re.compile(yml.get('pattern'))

        tokens = [self._u2str(e) for e in yml.get(key).get('tokens')]
        matches = [e for e in yml.get(key).get('matches')]
        expected = zip(tokens, matches)
        actual = list(self.split_pattern(text, pat1))

        self.assertEqual(expected, actual)

Example 39

Project: python-uncompyle6
Source File: aligner.py
View license
    def deparse_test(co):
        "This is a docstring"
        sys_version = sys.version_info.major + (sys.version_info.minor / 10.0)
        # deparsed = deparse_code(sys_version, co, showasm=True, showast=True)
        deparsed = align_deparse_code(sys_version, co, showasm=False, showast=False,
                                      showgrammar=False)
        print(deparsed.text)
        return

Example 40

Project: cert-viewer
Source File: forms.py
View license
def get_coerce_val():
    if sys.version_info.major < 3:
        coerce_val = unicode
    else:
        coerce_val = str
    return coerce_val

Example 41

Project: cocotb
Source File: decorators.py
View license
    def __call__(self, *args, **kwargs):
        try:
            return RunningCoroutine(self._func(*args, **kwargs), self)
        except Exception as e:
            traceback.print_exc()
            result = TestError(str(e))
            if sys.version_info.major >= 3:
                buff = StringIO()
                traceback.print_exc(file=buff)
            else:
                buff_bytes = BytesIO()
                traceback.print_exc(file=buff_bytes)
                buff = StringIO(buff_bytes.getvalue().decode("UTF-8"))
            result.stderr.write(buff.getvalue())
            raise result

Example 42

Project: defopt
Source File: test_defopt.py
View license
    @unittest.skipIf(sys.version_info.major == 2, 'Syntax not supported')
    def test_keyword_only(self):
        # Need to hide execution inside exec for Python 2's benefit.
        globals_ = {'self': self}
        exec(textwrap.dedent('''\
            def main(*, foo='bar'):
                """:type foo: str"""
                self.assertEqual(foo, 'baz')
                self.calls += 1
        '''), globals_)
        defopt.run(globals_['main'], argv=['--foo', 'baz'])
        self.assertEqual(self.calls, 1)

Example 43

Project: python3-trepan
Source File: cmdfns.py
View license
def deparse_fn(code):
    try:
        from uncompyle6.semantics.pysource import deparse_code
    except ImportError:
        return None
    sys_version = sys.version_info.major + (sys.version_info.minor / 10.0)
    try:
        out = io.StringIO()
        deparsed = deparse_code(sys_version, code, out)
        return deparsed.text
    except:
        raise
    return None

Example 44

Project: nanoservice
Source File: setup.py
View license
def read_long_description(readme_file):
    """ Read package long description from README file """
    try:
        import pypandoc
    except (ImportError, OSError) as exception:
        print('No pypandoc or pandoc: %s' % (exception,))
        if sys.version_info.major == 3:
            handle = open(readme_file, encoding='utf-8')
        else:
            handle = open(readme_file)
        long_description = handle.read()
        handle.close()
        return long_description
    else:
        return pypandoc.convert(readme_file, 'rst')

Example 45

Project: pelican-plugins
Source File: photos.py
View license
def galleries_string_decompose(gallery_string):
    splitter_regex = re.compile(r'[\s,]*?({photo}|{filename})')
    title_regex = re.compile(r'{(.+)}')
    galleries = map(unicode.strip if sys.version_info.major == 2 else str.strip, filter(None, splitter_regex.split(gallery_string)))
    galleries = [gallery[1:] if gallery.startswith('/') else gallery for gallery in galleries]
    if len(galleries) % 2 == 0 and u' ' not in galleries:
        galleries = zip(zip(['type'] * len(galleries[0::2]), galleries[0::2]), zip(['location'] * len(galleries[0::2]), galleries[1::2]))
        galleries = [dict(gallery) for gallery in galleries]
        for gallery in galleries:
            title = re.search(title_regex, gallery['location'])
            if title:
                gallery['title'] = title.group(1)
                gallery['location'] = re.sub(title_regex, '', gallery['location']).strip()
            else:
                gallery['title'] = DEFAULT_CONFIG['PHOTO_GALLERY_TITLE']
        return galleries
    else:
        logger.critical('Unexpected gallery location format! \n{}'.format(pprint.pformat(galleries)))
        raise Exception

Example 46

Project: python-opcua
Source File: xmlparser.py
View license
def ua_type_to_python(val, uatype):
    if uatype.startswith("Int") or uatype.startswith("UInt"):
        return int(val)
    elif uatype.lower().startswith("bool"):
        return _to_bool(val)
    elif uatype in ("Double", "Float"):
        return float(val)
    elif uatype == "String":
        return val
    elif uatype in ("Bytes", "Bytes", "ByteString", "ByteArray"):
        if sys.version_info.major > 2:
            return bytes(val, 'utf8')
        else:
            return val
    else:
        raise Exception("uatype nopt handled", uatype, " for val ", val)

Example 47

Project: PyBitmessage
Source File: openssl.py
View license
    def malloc(self, data, size):
        """
        returns a create_string_buffer (ctypes)
        """
        buffer = None
        if data != 0:
            if sys.version_info.major == 3 and isinstance(data, type('')):
                data = data.encode()
            buffer = self.create_string_buffer(data, size)
        else:
            buffer = self.create_string_buffer(size)
        return buffer

Example 48

Project: khayyam
Source File: helpers.py
View license
def force_encoded_string_output(func):  # pragma: no cover
    if sys.version_info.major < 3:
        def _func(*args, **kwargs):
            return func(*args, **kwargs).encode('utf-8')
        return _func
    else:
        return func

Example 49

Project: quack
Source File: quack.py
View license
def _prompt_to_create():
    """Prompt user to create quack configuration."""
    pyversion = sys.version_info.major
    prompt = input
    if pyversion < 3:
        prompt = raw_input
    yes_or_no = prompt(
        'No quack configuration found, do you want to create one? (y/N): ')
    if yes_or_no.lower() == 'y':
        project_name = prompt('Provide project name: ')
        with open('quack.yaml', 'a') as file_pointer:
            file_pointer.write("""name: %s
modules:
profiles:
  init:
    tasks: ['modules']""" % project_name)
        return _get_config()
    return

Example 50

Project: Ropper
Source File: coloredstring.py
View license
	def __new__(cls, data='', color=Color.LIGHT_GRAY):
		if isinstance(data, cstr):
			return data
		if version_info.major > 2 and type(data) is bytes:
			data = data.decode('utf-8')
		new = str.__new__(cls, data)
		new._color = color
		return new