當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。