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


Python six.PY3属性代码示例

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


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

示例1: convert_to_unicode

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def convert_to_unicode(text):
    """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
    if six.PY3:
        if isinstance(text, str):
            return text
        elif isinstance(text, bytes):
            return text.decode("utf-8", "ignore")
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    elif six.PY2:
        if isinstance(text, str):
            return text.decode("utf-8", "ignore")
        elif isinstance(text, unicode):
            return text
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    else:
        raise ValueError("Not running on Python2 or Python 3?") 
开发者ID:Socialbird-AILab,项目名称:BERT-Classification-Tutorial,代码行数:20,代码来源:tokenization.py

示例2: printable_text

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def printable_text(text):
    """Returns text encoded in a way suitable for print or `tf.logging`."""

    # These functions want `str` for both Python2 and Python3, but in one case
    # it's a Unicode string and in the other it's a byte string.
    if six.PY3:
        if isinstance(text, str):
            return text
        elif isinstance(text, bytes):
            return text.decode("utf-8", "ignore")
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    elif six.PY2:
        if isinstance(text, str):
            return text
        elif isinstance(text, unicode):
            return text.encode("utf-8")
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    else:
        raise ValueError("Not running on Python2 or Python 3?") 
开发者ID:Socialbird-AILab,项目名称:BERT-Classification-Tutorial,代码行数:23,代码来源:tokenization.py

示例3: test_mod_with_wrong_field_type_in_trans

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def test_mod_with_wrong_field_type_in_trans(self):
        msgid = "Correct type %(arg1)s"
        params = {'arg1': 'test1'}
        with mock.patch('gettext.translation') as trans:
            # Set up ugettext to return the original message with the
            # correct format string.
            trans.return_value.ugettext.return_value = msgid
            # Build a message and give it some parameters.
            result = _message.Message(msgid) % params
            # Now set up ugettext to return the translated version of
            # the original message, with a bad format string.
            wrong_type = u'Wrong type %(arg1)d'
            if six.PY3:
                trans.return_value.gettext.return_value = wrong_type
            else:
                trans.return_value.ugettext.return_value = wrong_type
            trans_result = result.translation()
            expected = msgid % params
            self.assertEqual(expected, trans_result) 
开发者ID:openstack,项目名称:oslo.i18n,代码行数:21,代码来源:test_message.py

示例4: _verify_docker_image_size

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def _verify_docker_image_size(self, image_name):
    """Verifies size of Docker image.

    Args:
      image_name: name of the Docker image.

    Returns:
      True if image size is withing the limits, False otherwise.
    """
    shell_call(['docker', 'pull', image_name])
    try:
      image_size = subprocess.check_output(
          ['docker', 'inspect', '--format={{.Size}}', image_name]).strip()
      image_size = int(image_size) if PY3 else long(image_size)
    except (ValueError, subprocess.CalledProcessError) as e:
      logging.error('Failed to determine docker image size: %s', e)
      return False
    logging.info('Size of docker image %s is %d', image_name, image_size)
    if image_size > MAX_DOCKER_IMAGE_SIZE:
      logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE)
    return image_size <= MAX_DOCKER_IMAGE_SIZE 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:23,代码来源:validate_submission_lib.py

示例5: _verify_docker_image_size

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def _verify_docker_image_size(self, image_name):
    """Verifies size of Docker image.

    Args:
      image_name: name of the Docker image.

    Returns:
      True if image size is within the limits, False otherwise.
    """
    shell_call(['docker', 'pull', image_name])
    try:
      image_size = subprocess.check_output(
          ['docker', 'inspect', '--format={{.Size}}', image_name]).strip()
      image_size = int(image_size) if PY3 else long(image_size)
    except (ValueError, subprocess.CalledProcessError) as e:
      logging.error('Failed to determine docker image size: %s', e)
      return False
    logging.info('Size of docker image %s is %d', image_name, image_size)
    if image_size > MAX_DOCKER_IMAGE_SIZE:
      logging.error('Image size exceeds limit %d', MAX_DOCKER_IMAGE_SIZE)
    return image_size <= MAX_DOCKER_IMAGE_SIZE 
开发者ID:StephanZheng,项目名称:neural-fingerprinting,代码行数:23,代码来源:validate_submission_lib.py

示例6: printable_text

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def printable_text(text):
    """    Returns text encoded in a way suitable for print or `tf.logging`.
        These functions want `str` for both Python2 and Python3, but in one case
        it's a Unicode string and in the other it's a byte string.
    """
    if six.PY3:
        if isinstance(text, str):
            return text
        elif isinstance(text, bytes):
            return text.decode("utf-8", "ignore")
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    elif six.PY2:
        if isinstance(text, str):
            return text
        elif isinstance(text, unicode):
            return text.encode("utf-8")
        else:
            raise ValueError("Unsupported string type: %s" % (type(text)))
    else:
        raise ValueError("Not running on Python2 or Python 3?") 
开发者ID:thunlp,项目名称:OpenNRE,代码行数:23,代码来源:utils.py

示例7: add_forks

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def add_forks(url, follow_next=True, **kwargs):
    """Add forks to the current project."""
    log.info('Open %s', url)
    try:
        response = urllib.request.urlopen(url, timeout=6)
    except urllib.error.URLError as ex:
        log.error(ex)
        return None

    if PY3 and response.status == 200 or response.code == 200:
        content = response.read().decode('utf-8')
        forks = json.loads(content)
        for fork in forks:
            add_interesting_fork(fork)
            git_remote_add(fork['owner']['login'], fork['clone_url'], **kwargs)
        # Gets link to next page.
        if follow_next:
            link = response.getheader('Link', '') if PY3 else dict(response.info()).get('link', '')
            match = re.match(r'<(.*)>;\ rel="next"', link)
            if match:
                return match.group(1)

    return None 
开发者ID:frost-nzcr4,项目名称:find_forks,代码行数:25,代码来源:find_forks.py

示例8: convert_to_unicode

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def convert_to_unicode(text):
  """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
  if six.PY3:
    if isinstance(text, str):
      return text
    elif isinstance(text, bytes):
      return text.decode("utf-8", "ignore")
    else:
      raise ValueError("Unsupported string type: %s" % (type(text)))
  elif six.PY2:
    if isinstance(text, str):
      return text.decode("utf-8", "ignore")
    elif isinstance(text, unicode):
      return text
    else:
      raise ValueError("Unsupported string type: %s" % (type(text)))
  else:
    raise ValueError("Not running on Python2 or Python 3?") 
开发者ID:fennuDetudou,项目名称:tudouNLP,代码行数:20,代码来源:tokenization.py

示例9: printable_text

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def printable_text(text):
  """Returns text encoded in a way suitable for print or `tf.logging`."""

  # These functions want `str` for both Python2 and Python3, but in one case
  # it's a Unicode string and in the other it's a byte string.
  if six.PY3:
    if isinstance(text, str):
      return text
    elif isinstance(text, bytes):
      return text.decode("utf-8", "ignore")
    else:
      raise ValueError("Unsupported string type: %s" % (type(text)))
  elif six.PY2:
    if isinstance(text, str):
      return text
    elif isinstance(text, unicode):
      return text.encode("utf-8")
    else:
      raise ValueError("Unsupported string type: %s" % (type(text)))
  else:
    raise ValueError("Not running on Python2 or Python 3?") 
开发者ID:fennuDetudou,项目名称:tudouNLP,代码行数:23,代码来源:tokenization.py

示例10: _parse

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def _parse(self, data):
        if six.PY3:
            result = {}
            for key, value in data.items():
                if isinstance(value, bytes):
                    value = utils.text(value)
                result[utils.text(key)] = value
            data = result

        for each in ('schedule', 'fetch', 'process', 'track'):
            if each in data:
                if data[each]:
                    data[each] = json.loads(data[each])
                else:
                    data[each] = {}
        if 'status' in data:
            data['status'] = int(data['status'])
        if 'lastcrawltime' in data:
            data['lastcrawltime'] = float(data['lastcrawltime'] or 0)
        if 'updatetime' in data:
            data['updatetime'] = float(data['updatetime'] or 0)
        return data 
开发者ID:binux,项目名称:pyspider,代码行数:24,代码来源:taskdb.py

示例11: get_encoding

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def get_encoding(headers, content):
    """Get encoding from request headers or page head."""
    encoding = None

    content_type = headers.get('content-type')
    if content_type:
        _, params = cgi.parse_header(content_type)
        if 'charset' in params:
            encoding = params['charset'].strip("'\"")

    if not encoding:
        content = utils.pretty_unicode(content[:1000]) if six.PY3 else content

        charset_re = re.compile(r'<meta.*?charset=["\']*(.+?)["\'>]',
                                flags=re.I)
        pragma_re = re.compile(r'<meta.*?content=["\']*;?charset=(.+?)["\'>]',
                               flags=re.I)
        xml_re = re.compile(r'^<\?xml.*?encoding=["\']*(.+?)["\'>]')
        encoding = (charset_re.findall(content) +
                    pragma_re.findall(content) +
                    xml_re.findall(content))
        encoding = encoding and encoding[0] or None

    return encoding 
开发者ID:binux,项目名称:pyspider,代码行数:26,代码来源:response.py

示例12: _request

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def _request(self, *args, **kwargs):
        if self.connection is None:
            self.connection = self.get_connection()
        self.connection.request(*args, **kwargs)
        response = self.connection.getresponse()

        status = response.status
        raw_body = response.read()
        try:
            if six.PY3:
                body = json.loads(raw_body.decode())
            else:
                body = json.loads(raw_body)
        except ValueError:
            body = None

        return _LXDResponse(status, raw_body, body) 
开发者ID:lxc,项目名称:pylxd,代码行数:19,代码来源:connection.py

示例13: postinit

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def postinit(self, args, body, decorators=None, returns=None):
        """Do some setup after initialisation.

        :param args: The arguments that the function takes.
        :type args: Arguments or list

        :param body: The contents of the function body.
        :type body: list(NodeNG)

        :param decorators: The decorators that are applied to this
            method or function.
        :type decorators: Decorators or None
        """
        self.args = args
        self.body = body
        self.decorators = decorators
        self.returns = returns

        if six.PY3 and isinstance(self.parent.frame(), ClassDef):
            self.set_local('__class__', self.parent.frame()) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:22,代码来源:scoped_nodes.py

示例14: process_tokens

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def process_tokens(self, tokens):
        # Process tokens and look for 'if' or 'elif'
        for index, token in enumerate(tokens):
            token_string = token[1]
            if token_string == 'elif':
                # AST exists by the time process_tokens is called, so
                # it's safe to assume tokens[index+1]
                # exists. tokens[index+1][2] is the elif's position as
                # reported by CPython and PyPy,
                # tokens[index][2] is the actual position and also is
                # reported by IronPython.
                self._elifs.extend([tokens[index][2], tokens[index+1][2]])
            elif six.PY3 and is_trailing_comma(tokens, index):
                if self.linter.is_message_enabled('trailing-comma-tuple'):
                    self.add_message('trailing-comma-tuple',
                                     line=token.start[0]) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:18,代码来源:refactoring.py

示例15: leave_functiondef

# 需要导入模块: import six [as 别名]
# 或者: from six import PY3 [as 别名]
def leave_functiondef(self, node):
        """on method node, check if this method couldn't be a function

        ignore class, static and abstract methods, initializer,
        methods overridden from a parent class.
        """
        if node.is_method():
            if node.args.args is not None:
                self._first_attrs.pop()
            if not self.linter.is_message_enabled('no-self-use'):
                return
            class_node = node.parent.frame()
            if (self._meth_could_be_func and node.type == 'method'
                    and node.name not in PYMETHODS
                    and not (node.is_abstract() or
                             overrides_a_method(class_node, node.name) or
                             decorated_with_property(node) or
                             (six.PY3 and _has_bare_super_call(node)))):
                self.add_message('no-self-use', node=node) 
开发者ID:AtomLinter,项目名称:linter-pylama,代码行数:21,代码来源:classes.py


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