Python sys 模块,version_info() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sys.version_info()

项目:Adafruit_Python_PureIO    作者:adafruit    | 项目源码 | 文件源码
def _do_download(version, download_base, to_dir, download_delay):
    egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
                       % (version, sys.version_info[0], sys.version_info[1]))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
                                      to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
        del sys.modules['pkg_resources']

    import setuptools
    setuptools.bootstrap_install_from = egg
项目:charm-plumgrid-gateway    作者:openstack    | 项目源码 | 文件源码
def current_version_string():
    """Current system python version as string major.minor.micro"""
    return "{0}.{1}.{2}".format(sys.version_info.major,
                                sys.version_info.minor,
                                sys.version_info.micro)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def write_exports(exports, stream):
    if sys.version_info[0] >= 3:
        # needs to be a text stream
        stream = codecs.getwriter('utf-8')(stream)
    cp = configparser.ConfigParser()
    for k, v in exports.items():
        # TODO check k, v for valid values
        cp.add_section(k)
        for entry in v.values():
            if entry.suffix is None:
                s = entry.prefix
            else:
                s = '%s:%s' % (entry.prefix, entry.suffix)
            if entry.flags:
                s = '%s [%s]' % (s, ', '.join(entry.flags))
            cp.set(k, entry.name, s)
    cp.write(stream)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def __init__(self, *args, **kw):
        if six.PY3:  # Python 3
            kw.pop('strict', None)

        # Pre-set source_address in case we have an older Python like 2.6.
        self.source_address = kw.get('source_address')

        if sys.version_info < (2, 7):  # Python 2.6
            # _HTTPConnection on Python 2.6 will balk at this keyword arg, but
            # not newer versions. We can still use it when creating a
            # connection though, so we pop it *after* we have saved it as
            # self.source_address.
            kw.pop('source_address', None)

        #: The socket options provided by the user. If no options are
        #: provided, we use the default options.
        self.socket_options = kw.pop('socket_options', self.default_socket_options)

        # Superclass also sets self.source_address in Python 2.7+.
        _HTTPConnection.__init__(self, *args, **kw)
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def _prepare_proxy(self, conn):
        """
        Establish tunnel connection early, because otherwise httplib
        would improperly set Host: header to proxy's IP:port.
        """
        # Python 2.7+
        try:
            set_tunnel = conn.set_tunnel
        except AttributeError:  # Platform-specific: Python 2.6
            set_tunnel = conn._set_tunnel

        if sys.version_info <= (2, 6, 4) and not self.proxy_headers:  # Python 2.6.4 and older
            set_tunnel(self.host, self.port)
        else:
            set_tunnel(self.host, self.port, self.proxy_headers)

        conn.connect()
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def check_requires_python(requires_python):
    """
    Check if the python version in use match the `requires_python` specifier.

    Returns `True` if the version of python in use matches the requirement.
    Returns `False` if the version of python in use does not matches the
    requirement.

    Raises an InvalidSpecifier if `requires_python` have an invalid format.
    """
    if requires_python is None:
        # The package provides no information
        return True
    requires_python_specifier = specifiers.SpecifierSet(requires_python)

    # We only use major.minor.micro
    python_version = version.parse('.'.join(map(str, sys.version_info[:3])))
    return python_version in requires_python_specifier
项目:python-    作者:secondtonone1    | 项目源码 | 文件源码
def check_dist_requires_python(dist):
    metadata = get_metadata(dist)
    feed_parser = FeedParser()
    feed_parser.feed(metadata)
    pkg_info_dict = feed_parser.close()
    requires_python = pkg_info_dict.get('Requires-Python')
    try:
        if not check_requires_python(requires_python):
            raise exceptions.UnsupportedPythonVersion(
                "%s requires Python '%s' but the running Python is %s" % (
                    dist.project_name,
                    requires_python,
                    '.'.join(map(str, sys.version_info[:3])),)
            )
    except specifiers.InvalidSpecifier as e:
        logger.warning(
            "Package %s has an invalid Requires-Python entry %s - %s" % (
                dist.project_name, requires_python, e))
        return
项目:py_find_1st    作者:roebel    | 项目源码 | 文件源码
def _do_download(version, download_base, to_dir, download_delay):
    egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
                       % (version, sys.version_info[0], sys.version_info[1]))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
                                      to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
        del sys.modules['pkg_resources']

    import setuptools
    setuptools.bootstrap_install_from = egg
项目:Adafruit_Python_PCA9685    作者:adafruit    | 项目源码 | 文件源码
def _do_download(version, download_base, to_dir, download_delay):
    egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
                       % (version, sys.version_info[0], sys.version_info[1]))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
                                      to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
        del sys.modules['pkg_resources']

    import setuptools
    setuptools.bootstrap_install_from = egg
项目:nidaqmx-python    作者:ni    | 项目源码 | 文件源码
def wrapped_ndpointer(*args, **kwargs):
    """
    Specifies an ndpointer type that wraps numpy.ctypeslib.ndpointer and
    allows a value of None to be passed to an argument of that type.

    Taken from http://stackoverflow.com/questions/32120178
    """
    if sys.version_info < (3,):
        if 'flags' in kwargs:
            kwargs['flags'] = tuple(
                f.encode('ascii') for f in kwargs['flags'])

    base = ndpointer(*args, **kwargs)

    def from_param(cls, obj):
        if obj is None:
            return obj
        return base.from_param(obj)

    return type(base.__name__, (base,),
                {'from_param': classmethod(from_param)})
项目:ios-xr-grpc-python    作者:cisco-grpc-connection-libs    | 项目源码 | 文件源码
def Parse(text, message, ignore_unknown_fields=False):
  """Parses a JSON representation of a protocol message into a message.
  Args:
    text: Message JSON representation.
    message: A protocol buffer message to merge into.
    ignore_unknown_fields: If True, do not raise errors for unknown fields.
  Returns:
    The same message passed as argument.
  Raises::
    ParseError: On JSON parsing problems.
  """
  if not isinstance(text, six.text_type): text = text.decode('utf-8')
  try:
    if sys.version_info < (2, 7):
      # object_pair_hook is not supported before python2.7
      js = json.loads(text)
    else:
      js = json.loads(text, object_pairs_hook=_DuplicateChecker)
  except ValueError as e:
    raise ParseError('Failed to load JSON: {0}.'.format(str(e)))
  return ParseDict(js, message, ignore_unknown_fields)
项目:SceneDensity    作者:ImOmid    | 项目源码 | 文件源码
def __getImageData(self, imageData, fmt="gif"):
        if fmt=="png":
            self.__importPngimagetk()
            if PngImageTk is False:
                raise Exception(
                    "TKINTERPNG library not found, PNG files not supported: " + imagePath)
            if sys.version_info >= (2, 7):
                self.warn(
                    "Image processing for .PNGs is slow. .GIF is the recommended format")
#                png = PngImageTk(imagePath)
#                png.convert()
#                photo = png.image
            else:
                raise Exception("PNG images only supported in python 3: " + imagePath)

        else:
            imgObj = PhotoImage(data=imageData)

        imgObj.path = None
        imgObj.modTime = datetime.datetime.now()
        imgObj.isAnimated = False
        imgObj.animating = False
        return imgObj

    # internal function to check/build image object
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def __init__(self, *args, **kw):
        if six.PY3:  # Python 3
            kw.pop('strict', None)

        # Pre-set source_address in case we have an older Python like 2.6.
        self.source_address = kw.get('source_address')

        if sys.version_info < (2, 7):  # Python 2.6
            # _HTTPConnection on Python 2.6 will balk at this keyword arg, but
            # not newer versions. We can still use it when creating a
            # connection though, so we pop it *after* we have saved it as
            # self.source_address.
            kw.pop('source_address', None)

        #: The socket options provided by the user. If no options are
        #: provided, we use the default options.
        self.socket_options = kw.pop('socket_options', self.default_socket_options)

        # Superclass also sets self.source_address in Python 2.7+.
        _HTTPConnection.__init__(self, *args, **kw)
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def _prepare_proxy(self, conn):
        """
        Establish tunnel connection early, because otherwise httplib
        would improperly set Host: header to proxy's IP:port.
        """
        # Python 2.7+
        try:
            set_tunnel = conn.set_tunnel
        except AttributeError:  # Platform-specific: Python 2.6
            set_tunnel = conn._set_tunnel

        if sys.version_info <= (2, 6, 4) and not self.proxy_headers:  # Python 2.6.4 and older
            set_tunnel(self._proxy_host, self.port)
        else:
            set_tunnel(self._proxy_host, self.port, self.proxy_headers)

        conn.connect()
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def write_exports(exports, stream):
    if sys.version_info[0] >= 3:
        # needs to be a text stream
        stream = codecs.getwriter('utf-8')(stream)
    cp = configparser.ConfigParser()
    for k, v in exports.items():
        # TODO check k, v for valid values
        cp.add_section(k)
        for entry in v.values():
            if entry.suffix is None:
                s = entry.prefix
            else:
                s = '%s:%s' % (entry.prefix, entry.suffix)
            if entry.flags:
                s = '%s [%s]' % (s, ', '.join(entry.flags))
            cp.set(k, entry.name, s)
    cp.write(stream)
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def __init__(self, *args, **kw):
        if six.PY3:  # Python 3
            kw.pop('strict', None)

        # Pre-set source_address in case we have an older Python like 2.6.
        self.source_address = kw.get('source_address')

        if sys.version_info < (2, 7):  # Python 2.6
            # _HTTPConnection on Python 2.6 will balk at this keyword arg, but
            # not newer versions. We can still use it when creating a
            # connection though, so we pop it *after* we have saved it as
            # self.source_address.
            kw.pop('source_address', None)

        #: The socket options provided by the user. If no options are
        #: provided, we use the default options.
        self.socket_options = kw.pop('socket_options', self.default_socket_options)

        # Superclass also sets self.source_address in Python 2.7+.
        _HTTPConnection.__init__(self, *args, **kw)
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def _prepare_proxy(self, conn):
        """
        Establish tunnel connection early, because otherwise httplib
        would improperly set Host: header to proxy's IP:port.
        """
        # Python 2.7+
        try:
            set_tunnel = conn.set_tunnel
        except AttributeError:  # Platform-specific: Python 2.6
            set_tunnel = conn._set_tunnel

        if sys.version_info <= (2, 6, 4) and not self.proxy_headers:  # Python 2.6.4 and older
            set_tunnel(self.host, self.port)
        else:
            set_tunnel(self.host, self.port, self.proxy_headers)

        conn.connect()
项目:my-first-blog    作者:AnkurBegining    | 项目源码 | 文件源码
def check_requires_python(requires_python):
    """
    Check if the python version in use match the `requires_python` specifier.

    Returns `True` if the version of python in use matches the requirement.
    Returns `False` if the version of python in use does not matches the
    requirement.

    Raises an InvalidSpecifier if `requires_python` have an invalid format.
    """
    if requires_python is None:
        # The package provides no information
        return True
    requires_python_specifier = specifiers.SpecifierSet(requires_python)

    # We only use major.minor.micro
    python_version = version.parse('.'.join(map(str, sys.version_info[:3])))
    return python_version in requires_python_specifier
项目:gee-bridge    作者:francbartoli    | 项目源码 | 文件源码
def BeginAsyncReader(self, xoff, yoff, xsize, ysize, buf_obj = None, buf_xsize = None, buf_ysize = None, buf_type = None, band_list = None, options=[]):
        if band_list is None:
            band_list = range(1, self.RasterCount + 1)
        if buf_xsize is None:
            buf_xsize = 0;
        if buf_ysize is None:
            buf_ysize = 0;
        if buf_type is None:
            buf_type = GDT_Byte

        if buf_xsize <= 0:
            buf_xsize = xsize
        if buf_ysize <= 0:
            buf_ysize = ysize

        if buf_obj is None:
            from sys import version_info
            nRequiredSize = int(buf_xsize * buf_ysize * len(band_list) * (_gdal.GetDataTypeSize(buf_type) / 8))
            if version_info >= (3,0,0):
                buf_obj_ar = [ None ]
                exec("buf_obj_ar[0] = b' ' * nRequiredSize")
                buf_obj = buf_obj_ar[0]
            else:
                buf_obj = ' ' * nRequiredSize
        return _gdal.Dataset_BeginAsyncReader(self, xoff, yoff, xsize, ysize, buf_obj, buf_xsize, buf_ysize, buf_type, band_list,  0, 0, 0, options)
项目:data_pipeline    作者:Yelp    | 项目源码 | 文件源码
def run(self):
        self.log.info("Python Version: {}".format(sys.version_info))
        is_success = True
        try:
            self.initial_action()
            self.process_table()
            self.log_info()
        except SystemExit:
            pass
        except Exception:
            if self.refresh_id:
                self.schematizer.update_refresh(
                    self.refresh_id,
                    RefreshStatus.FAILED,
                    self.processed_row_count
                )
            # Sends an email containing the exception encountered.
            self._email_exception_in_exception_context()
            is_success = False
        finally:
            # We don't want to drop the blackhole table until the replication handler is using
            # the schema_tracker database stably. (TODO: DATAPIPE-845)
            # self.final_action()
            if not is_success:
                os._exit(1)
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def _getuserbase():
    env_base = os.environ.get("IRONPYTHONUSERBASE", None)
    def joinuser(*args):
        return os.path.expanduser(os.path.join(*args))

    # what about 'os2emx', 'riscos' ?
    if os.name == "nt":
        base = os.environ.get("APPDATA") or "~"
        return env_base if env_base else joinuser(base, "Python")

    if sys.platform == "darwin":
        framework = get_config_var("PYTHONFRAMEWORK")
        if framework:
            return joinuser("~", "Library", framework, "%d.%d"%(
                sys.version_info[:2]))

    return env_base if env_base else joinuser("~", ".local")
项目:kinect-2-libras    作者:inessadl    | 项目源码 | 文件源码
def load_grammar(gt="Grammar.txt", gp=None,
                 save=True, force=False, logger=None):
    """Load the grammar (maybe from a pickle)."""
    if logger is None:
        logger = logging.getLogger()
    if gp is None:
        head, tail = os.path.splitext(gt)
        if tail == ".txt":
            tail = ""
        gp = head + tail + ".".join(map(str, sys.version_info)) + ".pickle"
    if force or not _newer(gp, gt):
        logger.info("Generating grammar tables from %s", gt)
        g = pgen.generate_grammar(gt)
        if save:
            logger.info("Writing grammar tables to %s", gp)
            try:
                g.dump(gp)
            except IOError, e:
                logger.info("Writing failed:"+str(e))
    else:
        g = grammar.Grammar()
        g.load(gp)
    return g
项目:BackManager    作者:linuxyan    | 项目源码 | 文件源码
def _do_download(version, download_base, to_dir, download_delay):
    """Download Setuptools."""
    egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
                       % (version, sys.version_info[0], sys.version_info[1]))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
                                      to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
        del sys.modules['pkg_resources']

    import setuptools
    setuptools.bootstrap_install_from = egg
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def read(self, iprot):
        if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
            iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.STRING:
                    self.name = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.STRING:
                    self.description = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def read(self, iprot):
        if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
            iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.MAP:
                    self.pspConfig = {}
                    (_ktype10, _vtype11, _size9) = iprot.readMapBegin()
                    for _i13 in range(_size9):
                        _key14 = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                        _val15 = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                        self.pspConfig[_key14] = _val15
                    iprot.readMapEnd()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def read(self, iprot):
        if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
            iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.timeoutMillis = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.STRING:
                    self.deviceName = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def read(self, iprot):
        if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
            iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.STRING:
                    self.remoteAddr = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def read(self, iprot):
        if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
            iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.STRING:
                    self.remoteAddr = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.I32:
                    self.serviceId = iprot.readI32()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def write(self, oprot):
        if oprot._fast_encode is not None and self.thrift_spec is not None:
            oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('serviceTotalPriceEvent_args')
        if self.remoteAddr is not None:
            oprot.writeFieldBegin('remoteAddr', TType.STRING, 1)
            oprot.writeString(self.remoteAddr.encode('utf-8') if sys.version_info[0] == 2 else self.remoteAddr)
            oprot.writeFieldEnd()
        if self.serviceID is not None:
            oprot.writeFieldBegin('serviceID', TType.I32, 2)
            oprot.writeI32(self.serviceID)
            oprot.writeFieldEnd()
        if self.totalPriceResp is not None:
            oprot.writeFieldBegin('totalPriceResp', TType.STRUCT, 3)
            self.totalPriceResp.write(oprot)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def read(self, iprot):
        if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
            iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.STRING:
                    self.msg = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def read(self, iprot):
        if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
            iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.STRING:
                    self.message = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def read(self, iprot):
        if iprot._fast_decode is not None and isinstance(iprot.trans, TTransport.CReadableTransport) and self.thrift_spec is not None:
            iprot._fast_decode(self, iprot, (self.__class__, self.thrift_spec))
            return
        iprot.readStructBegin()
        while True:
            (fname, ftype, fid) = iprot.readFieldBegin()
            if ftype == TType.STOP:
                break
            if fid == 1:
                if ftype == TType.I32:
                    self.amount = iprot.readI32()
                else:
                    iprot.skip(ftype)
            elif fid == 2:
                if ftype == TType.STRING:
                    self.currencyCode = iprot.readString().decode('utf-8') if sys.version_info[0] == 2 else iprot.readString()
                else:
                    iprot.skip(ftype)
            else:
                iprot.skip(ftype)
            iprot.readFieldEnd()
        iprot.readStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def write(self, oprot):
        if oprot._fast_encode is not None and self.thrift_spec is not None:
            oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('ServiceDetails')
        if self.serviceId is not None:
            oprot.writeFieldBegin('serviceId', TType.I32, 1)
            oprot.writeI32(self.serviceId)
            oprot.writeFieldEnd()
        if self.serviceDescription is not None:
            oprot.writeFieldBegin('serviceDescription', TType.STRING, 2)
            oprot.writeString(self.serviceDescription.encode('utf-8') if sys.version_info[0] == 2 else self.serviceDescription)
            oprot.writeFieldEnd()
        if self.serviceName is not None:
            oprot.writeFieldBegin('serviceName', TType.STRING, 3)
            oprot.writeString(self.serviceName.encode('utf-8') if sys.version_info[0] == 2 else self.serviceName)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()
项目:wpw-sdk-python    作者:WPTechInnovation    | 项目源码 | 文件源码
def write(self, oprot):
        if oprot._fast_encode is not None and self.thrift_spec is not None:
            oprot.trans.write(oprot._fast_encode(self, (self.__class__, self.thrift_spec)))
            return
        oprot.writeStructBegin('PaymentResponse')
        if self.serverId is not None:
            oprot.writeFieldBegin('serverId', TType.STRING, 1)
            oprot.writeString(self.serverId.encode('utf-8') if sys.version_info[0] == 2 else self.serverId)
            oprot.writeFieldEnd()
        if self.clientId is not None:
            oprot.writeFieldBegin('clientId', TType.STRING, 2)
            oprot.writeString(self.clientId.encode('utf-8') if sys.version_info[0] == 2 else self.clientId)
            oprot.writeFieldEnd()
        if self.totalPaid is not None:
            oprot.writeFieldBegin('totalPaid', TType.I32, 3)
            oprot.writeI32(self.totalPaid)
            oprot.writeFieldEnd()
        if self.serviceDeliveryToken is not None:
            oprot.writeFieldBegin('serviceDeliveryToken', TType.STRUCT, 4)
            self.serviceDeliveryToken.write(oprot)
            oprot.writeFieldEnd()
        oprot.writeFieldStop()
        oprot.writeStructEnd()
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxReadForceSensor(clientID, forceSensorHandle, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''
    state = ct.c_ubyte()
    forceVector  = (ct.c_float*3)()
    torqueVector = (ct.c_float*3)()
    ret = c_ReadForceSensor(clientID, forceSensorHandle, ct.byref(state), forceVector, torqueVector, operationMode)
    arr1 = []
    for i in range(3):
        arr1.append(forceVector[i])
    arr2 = []
    for i in range(3):
        arr2.append(torqueVector[i])
    #if sys.version_info[0] == 3:
    #    state=state.value
    #else:
    #    state=ord(state.value)
    return ret, state.value, arr1, arr2
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxLoadUI(clientID, uiPathAndName, options, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''

    count = ct.c_int()
    uiHandles = ct.POINTER(ct.c_int)()
    if (sys.version_info[0] == 3) and (type(uiPathAndName) is str):
        uiPathAndName=uiPathAndName.encode('utf-8')
    ret = c_LoadUI(clientID, uiPathAndName, options, ct.byref(count), ct.byref(uiHandles), operationMode)

    handles = []
    if ret == 0:
        for i in range(count.value):
            handles.append(uiHandles[i])
        #free C buffers
        c_ReleaseBuffer(uiHandles)

    return ret, handles
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxAuxiliaryConsoleOpen(clientID, title, maxLines, mode, position, size, textColor, backgroundColor, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''

    consoleHandle = ct.c_int()
    if (sys.version_info[0] == 3) and (type(title) is str):
        title=title.encode('utf-8')
    if position != None:
        c_position = (ct.c_int*2)(*position)
    else:
        c_position = None
    if size != None:
        c_size = (ct.c_int*2)(*size)
    else:
        c_size = None
    if textColor != None:
        c_textColor = (ct.c_float*3)(*textColor)
    else:
        c_textColor = None
    if backgroundColor != None:
        c_backgroundColor = (ct.c_float*3)(*backgroundColor)
    else:
        c_backgroundColor = None
    return c_AuxiliaryConsoleOpen(clientID, title, maxLines, mode, c_position, c_size, c_textColor, c_backgroundColor, ct.byref(consoleHandle), operationMode), consoleHandle.value
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxGetLastErrors(clientID, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''
    errors =[]
    errorCnt = ct.c_int()
    errorStrings = ct.POINTER(ct.c_char)()
    ret = c_GetLastErrors(clientID, ct.byref(errorCnt), ct.byref(errorStrings), operationMode)
    if ret == 0:
        s = 0
        for i in range(errorCnt.value):
            a = bytearray()
            while errorStrings[s] != b'\0':
                if sys.version_info[0] == 3:
                    a.append(int.from_bytes(errorStrings[s],'big'))
                else:
                    a.append(errorStrings[s])
                s += 1
            s += 1 #skip null
            if sys.version_info[0] == 3:
                errors.append(str(a,'utf-8'))
            else:
                errors.append(str(a))

    return ret, errors
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxDisplayDialog(clientID, titleText, mainText, dialogType, initialText, titleColors, dialogColors, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''
    if titleColors != None:
        c_titleColors  = (ct.c_float*6)(*titleColors)
    else:
        c_titleColors  = None
    if dialogColors != None:
        c_dialogColors  = (ct.c_float*6)(*dialogColors)
    else:
        c_dialogColors  = None

    c_dialogHandle = ct.c_int()
    c_uiHandle = ct.c_int()
    if sys.version_info[0] == 3:
        if type(titleText) is str:
            titleText=titleText.encode('utf-8')
        if type(mainText) is str:
            mainText=mainText.encode('utf-8')
        if type(initialText) is str:
            initialText=initialText.encode('utf-8')
    return c_DisplayDialog(clientID, titleText, mainText, dialogType, initialText, c_titleColors, c_dialogColors, ct.byref(c_dialogHandle), ct.byref(c_uiHandle), operationMode), c_dialogHandle.value, c_uiHandle.value
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxGetDialogInput(clientID, dialogHandle, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''
    inputText = ct.POINTER(ct.c_char)()
    ret = c_GetDialogInput(clientID, dialogHandle, ct.byref(inputText), operationMode)

    a = bytearray()
    if ret == 0:
        i = 0
        while inputText[i] != b'\0':
            if sys.version_info[0] == 3:
                a.append(int.from_bytes(inputText[i],'big'))
            else:
                a.append(inputText[i])
            i = i+1

    if sys.version_info[0] == 3:
        a=str(a,'utf-8')
    else:
        a=str(a)
    return ret, a
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxGetStringSignal(clientID, signalName, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''

    signalLength = ct.c_int();
    signalValue = ct.POINTER(ct.c_ubyte)()
    if (sys.version_info[0] == 3) and (type(signalName) is str):
        signalName=signalName.encode('utf-8')
    ret = c_GetStringSignal(clientID, signalName, ct.byref(signalValue), ct.byref(signalLength), operationMode)

    a = bytearray()
    if ret == 0:
        for i in range(signalLength.value):
            a.append(signalValue[i])
    if sys.version_info[0] != 3:
        a=str(a)

    return ret, a
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxReadStringStream(clientID, signalName, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''

    signalLength = ct.c_int();
    signalValue = ct.POINTER(ct.c_ubyte)()
    if (sys.version_info[0] == 3) and (type(signalName) is str):
        signalName=signalName.encode('utf-8')
    ret = c_ReadStringStream(clientID, signalName, ct.byref(signalValue), ct.byref(signalLength), operationMode)

    a = bytearray()
    if ret == 0:
        for i in range(signalLength.value):
            a.append(signalValue[i])
    if sys.version_info[0] != 3:
        a=str(a)

    return ret, a
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxSetStringSignal(clientID, signalName, signalValue, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''

    sigV=signalValue
    if sys.version_info[0] == 3:
        if type(signalName) is str:
            signalName=signalName.encode('utf-8')
        if type(signalValue) is bytearray:
            sigV  = (ct.c_ubyte*len(signalValue))(*signalValue)
        if type(signalValue) is str:
            signalValue=signalValue.encode('utf-8')
            sigV  = (ct.c_ubyte*len(signalValue))(*signalValue)
    else:
        if type(signalValue) is bytearray:
            sigV = (ct.c_ubyte*len(signalValue))(*signalValue)
        if type(signalValue) is str:
            signalValue=bytearray(signalValue)
            sigV = (ct.c_ubyte*len(signalValue))(*signalValue)
    sigV=ct.cast(sigV,ct.POINTER(ct.c_ubyte)) # IronPython needs this
    return c_SetStringSignal(clientID, signalName, sigV, len(signalValue), operationMode)
项目:mazerunner    作者:lucasdavid    | 项目源码 | 文件源码
def simxAppendStringSignal(clientID, signalName, signalValue, operationMode):
    '''
    Please have a look at the function description/documentation in the V-REP user manual
    '''

    sigV=signalValue
    if sys.version_info[0] == 3:
        if type(signalName) is str:
            signalName=signalName.encode('utf-8')
        if type(signalValue) is bytearray:
            sigV  = (ct.c_ubyte*len(signalValue))(*signalValue)
        if type(signalValue) is str:
            signalValue=signalValue.encode('utf-8')
            sigV  = (ct.c_ubyte*len(signalValue))(*signalValue)
    else:
        if type(signalValue) is bytearray:
            sigV = (ct.c_ubyte*len(signalValue))(*signalValue)
        if type(signalValue) is str:
            signalValue=bytearray(signalValue)
            sigV = (ct.c_ubyte*len(signalValue))(*signalValue)
    sigV=ct.cast(sigV,ct.POINTER(ct.c_ubyte)) # IronPython needs this
    return c_AppendStringSignal(clientID, signalName, sigV, len(signalValue), operationMode)
项目:Adafruit_Python_ADS1x15    作者:adafruit    | 项目源码 | 文件源码
def _do_download(version, download_base, to_dir, download_delay):
    egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
                       % (version, sys.version_info[0], sys.version_info[1]))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
                                      to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
        del sys.modules['pkg_resources']

    import setuptools
    setuptools.bootstrap_install_from = egg
项目:googletranslate.popclipext    作者:wizyoung    | 项目源码 | 文件源码
def __init__(self, *args, **kw):
        if six.PY3:  # Python 3
            kw.pop('strict', None)

        # Pre-set source_address in case we have an older Python like 2.6.
        self.source_address = kw.get('source_address')

        if sys.version_info < (2, 7):  # Python 2.6
            # _HTTPConnection on Python 2.6 will balk at this keyword arg, but
            # not newer versions. We can still use it when creating a
            # connection though, so we pop it *after* we have saved it as
            # self.source_address.
            kw.pop('source_address', None)

        #: The socket options provided by the user. If no options are
        #: provided, we use the default options.
        self.socket_options = kw.pop('socket_options', self.default_socket_options)

        # Superclass also sets self.source_address in Python 2.7+.
        _HTTPConnection.__init__(self, *args, **kw)
项目:googletranslate.popclipext    作者:wizyoung    | 项目源码 | 文件源码
def _prepare_proxy(self, conn):
        """
        Establish tunnel connection early, because otherwise httplib
        would improperly set Host: header to proxy's IP:port.
        """
        # Python 2.7+
        try:
            set_tunnel = conn.set_tunnel
        except AttributeError:  # Platform-specific: Python 2.6
            set_tunnel = conn._set_tunnel

        if sys.version_info <= (2, 6, 4) and not self.proxy_headers:  # Python 2.6.4 and older
            set_tunnel(self._proxy_host, self.port)
        else:
            set_tunnel(self._proxy_host, self.port, self.proxy_headers)

        conn.connect()
项目:PyJFuzz    作者:mseclab    | 项目源码 | 文件源码
def need_update(self):
        if "HTTP_PROXY" in os.environ or "HTTPS_PROXY" in os.environ:
            if "HTTP_PROXY" in os.environ:
                if sys.version_info >= (3, 0):
                    proxy = urllib.parse.urlparse(os.environ["HTTP_PROXY"])
                else:
                    proxy = urlparse.urlparse(os.environ["HTTP_PROXY"])
            else:
                if sys.version_info >= (3, 0):
                    proxy = urllib.parse.urlparse(os.environ["HTTPS_PROXY"])
                else:
                    proxy = urlparse.urlparse(os.environ["HTTPS_PROXY"])
            if sys.version_info >= (3, 0):
                conn = http.client.HTTPSConnection(proxy.hostname, proxy.port)
            else:
                conn = httplib.HTTPSConnection(proxy.hostname, proxy.port)
            conn.set_tunnel(self.version_host, 443)
        else:
            if sys.version_info >= (3, 0):
                conn = http.client.HTTPSConnection("raw.githubusercontent.com")
            else:
                conn = httplib.HTTPSConnection("raw.githubusercontent.com")
        conn.request("GET", self.version_url)
        version = conn.getresponse().read()
        try:
            if StrictVersion(version) > StrictVersion(PYJFUZZ_VERSION):
                self.new_version = version
                return True
        except:
            pass
        return False
项目:ccu_and_eccu_publish    作者:gaofubin    | 项目源码 | 文件源码
def _do_download(version, download_base, to_dir, download_delay):
    egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg'
                       % (version, sys.version_info[0], sys.version_info[1]))
    if not os.path.exists(egg):
        archive = download_setuptools(version, download_base,
                                      to_dir, download_delay)
        _build_egg(egg, archive, to_dir)
    sys.path.insert(0, egg)

    # Remove previously-imported pkg_resources if present (see
    # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details).
    if 'pkg_resources' in sys.modules:
        del sys.modules['pkg_resources']

    import setuptools
    setuptools.bootstrap_install_from = egg
项目:python-zwoasi    作者:stevemarple    | 项目源码 | 文件源码
def get_dict(self):
        r = {}
        for k, _ in self._fields_:
            v = getattr(self, k)
            if sys.version_info[0] >= 3 and isinstance(v, bytes):
                v = v.decode()
            r[k] = v
        del r['Unused']

        r['SupportedBins'] = []
        for i in range(len(self.SupportedBins)):
            if self.SupportedBins[i]:
                r['SupportedBins'].append(self.SupportedBins[i])
            else:
                break
        r['SupportedVideoFormat'] = []
        for i in range(len(self.SupportedVideoFormat)):
            if self.SupportedVideoFormat[i] == ASI_IMG_END:
                break
            r['SupportedVideoFormat'].append(self.SupportedVideoFormat[i])

        for k in ('IsColorCam', 'MechanicalShutter', 'IsCoolerCam',
                  'IsUSB3Host', 'IsUSB3Camera'):
            r[k] = bool(getattr(self, k))
        return r