python类PY2的实例源码

example.py 文件源码 项目:text 作者: pytorch 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def fromCSV(cls, data, fields):
        data = data.rstrip("\n")
        # If Python 2, encode to utf-8 since CSV doesn't take unicode input
        if six.PY2:
            data = data.encode('utf-8')
        # Use Python CSV module to parse the CSV line
        parsed_csv_lines = csv.reader([data])

        # If Python 2, decode back to unicode (the original input format).
        if six.PY2:
            for line in parsed_csv_lines:
                parsed_csv_line = [six.text_type(col, 'utf-8') for col in line]
                break
        else:
            parsed_csv_line = list(parsed_csv_lines)[0]
        return cls.fromlist(parsed_csv_line, fields)
mock.py 文件源码 项目:auger 作者: laffra 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _copy_func_details(func, funcopy):
    funcopy.__name__ = func.__name__
    funcopy.__doc__ = func.__doc__
    try:
        funcopy.__text_signature__ = func.__text_signature__
    except AttributeError:
        pass
    # we explicitly don't copy func.__dict__ into this copy as it would
    # expose original attributes that should be mocked
    try:
        funcopy.__module__ = func.__module__
    except AttributeError:
        pass
    try:
        funcopy.__defaults__ = func.__defaults__
    except AttributeError:
        pass
    try:
        funcopy.__kwdefaults__ = func.__kwdefaults__
    except AttributeError:
        pass
    if six.PY2:
        funcopy.func_defaults = func.func_defaults
        return
mock.py 文件源码 项目:auger 作者: laffra 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def assert_called_with(_mock_self, *args, **kwargs):
        """assert that the mock was called with the specified arguments.

        Raises an AssertionError if the args and keyword args passed in are
        different to the last call to the mock."""
        self = _mock_self
        if self.call_args is None:
            expected = self._format_mock_call_signature(args, kwargs)
            raise AssertionError('Expected call: %s\nNot called' % (expected,))

        def _error_message(cause):
            msg = self._format_mock_failure_message(args, kwargs)
            if six.PY2 and cause is not None:
                # Tack on some diagnostics for Python without __cause__
                msg = '%s\n%s' % (msg, str(cause))
            return msg
        expected = self._call_matcher((args, kwargs))
        actual = self._call_matcher(self.call_args)
        if expected != actual:
            cause = expected if isinstance(expected, Exception) else None
            six.raise_from(AssertionError(_error_message(cause)), cause)
mock.py 文件源码 项目:auger 作者: laffra 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def _format_call_signature(name, args, kwargs):
    message = '%s(%%s)' % name
    formatted_args = ''
    args_string = ', '.join([repr(arg) for arg in args])

    def encode_item(item):
        if six.PY2 and isinstance(item, unicode):
            return item.encode("utf-8")
        else:
            return item

    kwargs_string = ', '.join([
        '%s=%r' % (encode_item(key), value) for key, value in sorted(kwargs.items())
    ])
    if args_string:
        formatted_args = args_string
    if kwargs_string:
        if formatted_args:
            formatted_args += ', '
        formatted_args += kwargs_string

    return message % formatted_args
test_stat_calculate_methods.py 文件源码 项目:plotnine 作者: has2k1 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def test_stat_bin():
    x = [1, 2, 3]
    y = [1, 2, 3]
    df = pd.DataFrame({'x': x, 'y': y})

    # About the default bins
    gg = ggplot(aes(x='x'), df) + stat_bin()

    if not six.PY2:
        # Test fails on PY2 when all the tests are run,
        # but not when only this test module is run
        with pytest.warns(None) as record:
            gg.draw_test()

        res = ('bins' in str(item.message).lower() for item in record)
        assert any(res)

    # About the ignoring the y aesthetic
    gg = ggplot(aes(x='x', y='y'), df) + stat_bin()
    with pytest.raises(PlotnineError):
        gg.draw_test()
test_geom_rug.py 文件源码 项目:plotnine 作者: has2k1 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def test_aesthetics():
    p = (ggplot(df) +
         geom_rug(aes('x', 'y'), size=2) +
         geom_rug(aes('x+2*n', 'y+2*n', alpha='z'),
                  size=2, sides='tr') +
         geom_rug(aes('x+4*n', 'y+4*n', linetype='factor(z)'),
                  size=2, sides='t') +
         geom_rug(aes('x+6*n', 'y+6*n', color='factor(z)'),
                  size=2, sides='b') +
         geom_rug(aes('x+8*n', 'y+8*n', size='z'),
                  sides='tblr'))

    if six.PY2:
        # Small displacement in y-axis text
        assert p + _theme == ('aesthetics', {'tol': 4})
    else:
        assert p + _theme == 'aesthetics'
utils.py 文件源码 项目:panko 作者: openstack 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def decode_unicode(input):
    """Decode the unicode of the message, and encode it into utf-8."""
    if isinstance(input, dict):
        temp = {}
        # If the input data is a dict, create an equivalent dict with a
        # predictable insertion order to avoid inconsistencies in the
        # message signature computation for equivalent payloads modulo
        # ordering
        for key, value in sorted(six.iteritems(input)):
            temp[decode_unicode(key)] = decode_unicode(value)
        return temp
    elif isinstance(input, (tuple, list)):
        # When doing a pair of JSON encode/decode operations to the tuple,
        # the tuple would become list. So we have to generate the value as
        # list here.
        return [decode_unicode(element) for element in input]
    elif six.PY2 and isinstance(input, six.text_type):
        return input.encode('utf-8')
    elif six.PY3 and isinstance(input, six.binary_type):
        return input.decode('utf-8')
    else:
        return input
__init__.py 文件源码 项目:devsecops-example-helloworld 作者: boozallen 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _some_str(value):
    try:
        if PY2:
            # If there is a working __unicode__, great.
            # Otherwise see if we can get a bytestring...
            # Otherwise we fallback to unprintable.
            try:
                return unicode(value)
            except:
                return "b%s" % repr(str(value))
        else:
            # For Python3, bytestrings don't implicit decode, so its trivial.
            return str(value)
    except:
        return '<unprintable %s object>' % type(value).__name__

# --
evaljs.py 文件源码 项目:tvlinker 作者: ozmartian 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def console(self):
        """starts to interact (starts interactive console) Something like code.InteractiveConsole"""
        while True:
            if six.PY2:
                code = raw_input('>>> ')
            else:
                code = input('>>>')
            try:
                print(self.eval(code))
            except KeyboardInterrupt:
                break
            except Exception as e:
                import traceback
                if DEBUG:
                    sys.stderr.write(traceback.format_exc())
                else:
                    sys.stderr.write('EXCEPTION: '+str(e)+'\n')
                time.sleep(0.01)




#print x
test_config.py 文件源码 项目:simpleswitch2 作者: inside-openflow 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def setUp(self):
        # Example intentionally not in order
        example = """
        [ACL]
        foo.baz: ACL
        foo.acl: ACL
        [ACL/Rule A]
        foo.bar: ACL-Rule-A
        [ACL/Rule B]
        foo.baz: ACL-Rule-B
        [DEFAULTS]
        foo.bar: Default
        foo.baz: Default
        [Deep/Subsection/Without/Parents]
        foo.baz: Deep
        [ACL/DEFAULTS]
        foo.bar: ACL-Default
        foo.baz: ACL-Default
        """

        self.parser = config.ConfigParser()
        if six.PY2:
            self.parser.readfp(io.BytesIO(dedent(example)))
        else:
            self.parser.read_string(example)
__init__.py 文件源码 项目:deb-python-traceback2 作者: openstack 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _some_str(value):
    try:
        if PY2:
            # If there is a working __unicode__, great.
            # Otherwise see if we can get a bytestring...
            # Otherwise we fallback to unprintable.
            try:
                return unicode(value)
            except:
                return "b%s" % repr(str(value))
        else:
            # For Python3, bytestrings don't implicit decode, so its trivial.
            return str(value)
    except:
        return '<unprintable %s object>' % type(value).__name__

# --
manager.py 文件源码 项目:OpenStackClient_VBS 作者: Huawei 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def mixin_meta(item, resp):
        if isinstance(item, six.string_types):
            if six.PY2 and isinstance(item, six.text_type):
                return resource.UnicodeWithMeta(item, resp)
            else:
                return resource.StrWithMeta(item, resp)
        elif isinstance(item, six.binary_type):
            return resource.BytesWithMeta(item, resp)
        elif isinstance(item, list):
            return resource.ListWithMeta(item, resp)
        elif isinstance(item, tuple):
            return resource.TupleWithMeta(item, resp)
        elif item is None:
            return resource.TupleWithMeta((), resp)
        else:
            return resource.DictWithMeta(item, resp)
utils.py 文件源码 项目:SlackPoloBot 作者: omaidf 项目源码 文件源码 阅读 75 收藏 0 点赞 0 评论 0
def to_utf8(s):
    """Convert a string to utf8. If the argument is an iterable
    (list/tuple/set), then each element of it would be converted instead.

    >>> to_utf8('a')
    'a'
    >>> to_utf8(u'a')
    'a'
    >>> to_utf8([u'a', u'b', u'\u4f60'])
    ['a', 'b', '\\xe4\\xbd\\xa0']
    """
    if six.PY2:
        if isinstance(s, str):
            return s
        elif isinstance(s, unicode):
            return s.encode('utf-8')
        elif isinstance(s, (list, tuple, set)):
            return [to_utf8(v) for v in s]
        else:
            return s
    else:
        return s
logsetup.py 文件源码 项目:psyplot 作者: Chilipp 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _get_home():
    """Find user's home directory if possible.
    Otherwise, returns None.

    :see:  http://mail.python.org/pipermail/python-list/2005-February/325395.html

    This function is copied from matplotlib version 1.4.3, Jan 2016
    """
    try:
        if six.PY2 and sys.platform == 'win32':
            path = os.path.expanduser(b"~").decode(sys.getfilesystemencoding())
        else:
            path = os.path.expanduser("~")
    except ImportError:
        # This happens on Google App Engine (pwd module is not present).
        pass
    else:
        if os.path.isdir(path):
            return path
    for evar in ('HOME', 'USERPROFILE', 'TMP'):
        path = os.environ.get(evar)
        if path is not None and os.path.isdir(path):
            return path
    return None
test_main.py 文件源码 项目:psyplot 作者: Chilipp 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_main_01_from_project(self):
        """Test the :func:`psyplot.__main__.main` function"""
        if not six.PY2:
            with self.assertRaisesRegex(ValueError, 'filename'):
                main.main(['-o', 'test.pdf'])
        sp, fname1 = self._create_and_save_test_project()
        fname2 = tempfile.NamedTemporaryFile(
                    suffix='.pdf', prefix='test_psyplot_').name
        self._created_files.add(fname2)
        sp.save_project(fname1, use_rel_paths=False)
        psy.close('all')
        if six.PY2:
            main.main(['-p', fname1, '-o', fname2])
        else:
            with self.assertWarnsRegex(UserWarning, 'ignored'):
                main.main(['-p', fname1, '-o', fname2, '-n', 't2m'])
        self.assertTrue(osp.exists(fname2), msg='Missing ' + fname2)
        self.assertEqual(len(psy.gcp(True)), 4)
json_util.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def decode_b64jose(data, size=None, minimum=False):
    """Decode JOSE Base-64 field.

    :param unicode data:
    :param int size: Required length (after decoding).
    :param bool minimum: If ``True``, then `size` will be treated as
        minimum required length, as opposed to exact equality.

    :rtype: bytes

    """
    error_cls = TypeError if six.PY2 else binascii.Error
    try:
        decoded = b64.b64decode(data.encode())
    except error_cls as error:
        raise errors.DeserializationError(error)

    if size is not None and ((not minimum and len(decoded) != size) or
                             (minimum and len(decoded) < size)):
        raise errors.DeserializationError(
            "Expected at least or exactly {0} bytes".format(size))

    return decoded
json_util.py 文件源码 项目:TCP-IP 作者: JackZ0 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def decode_hex16(value, size=None, minimum=False):
    """Decode hexlified field.

    :param unicode value:
    :param int size: Required length (after decoding).
    :param bool minimum: If ``True``, then `size` will be treated as
        minimum required length, as opposed to exact equality.

    :rtype: bytes

    """
    value = value.encode()
    if size is not None and ((not minimum and len(value) != size * 2) or
                             (minimum and len(value) < size * 2)):
        raise errors.DeserializationError()
    error_cls = TypeError if six.PY2 else binascii.Error
    try:
        return binascii.unhexlify(value)
    except error_cls as error:
        raise errors.DeserializationError(error)
packages.py 文件源码 项目:charm-nova-compute 作者: openstack 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def pip_execute(*args, **kwargs):
    """Overriden pip_execute() to stop sys.path being changed.

    The act of importing main from the pip module seems to cause add wheels
    from the /usr/share/python-wheels which are installed by various tools.
    This function ensures that sys.path remains the same after the call is
    executed.
    """
    try:
        _path = sys.path
        try:
            from pip import main as _pip_execute
        except ImportError:
            apt_update()
            if six.PY2:
                apt_install('python-pip')
            else:
                apt_install('python3-pip')
            from pip import main as _pip_execute
        _pip_execute(*args, **kwargs)
    finally:
        sys.path = _path
ip.py 文件源码 项目:charm-nova-compute 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def ns_query(address):
    try:
        import dns.resolver
    except ImportError:
        if six.PY2:
            apt_install('python-dnspython', fatal=True)
        else:
            apt_install('python3-dnspython', fatal=True)
        import dns.resolver

    if isinstance(address, dns.name.Name):
        rtype = 'PTR'
    elif isinstance(address, six.string_types):
        rtype = 'A'
    else:
        return None

    try:
        answers = dns.resolver.query(address, rtype)
    except dns.resolver.NXDOMAIN:
        return None

    if answers:
        return str(answers[0])
    return None
packages.py 文件源码 项目:charm-nova-compute 作者: openstack 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def pip_execute(*args, **kwargs):
    """Overriden pip_execute() to stop sys.path being changed.

    The act of importing main from the pip module seems to cause add wheels
    from the /usr/share/python-wheels which are installed by various tools.
    This function ensures that sys.path remains the same after the call is
    executed.
    """
    try:
        _path = sys.path
        try:
            from pip import main as _pip_execute
        except ImportError:
            apt_update()
            if six.PY2:
                apt_install('python-pip')
            else:
                apt_install('python3-pip')
            from pip import main as _pip_execute
        _pip_execute(*args, **kwargs)
    finally:
        sys.path = _path


问题


面经


文章

微信
公众号

扫码关注公众号