1

我有一连串在 Travis CI 上运行的单元测试,并且在 PY3.2 上运行。我怎样才能在不使用 Six.u() 的情况下解决这个问题?

def test_parse_utf8(self):
    s = String("foo", 12, encoding="utf8")
    self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u"hello joh\u0503n")

======================================================================
ERROR: Failure: SyntaxError (invalid syntax (test_strings.py, line 37))
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/failure.py", line 39, in runTest
    raise self.exc_val.with_traceback(self.tb)
  File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/loader.py", line 414, in loadTestsFromName
    addr.filename, addr.module)
  File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 47, in importFromPath
    return self.importFromDir(dir_path, fqname)
  File "/home/travis/virtualenv/python3.2.5/lib/python3.2/site-packages/nose/importer.py", line 94, in importFromDir
    mod = load_module(part_fqname, fh, filename, desc)
  File "/home/travis/build/construct/construct/tests/test_strings.py", line 37
    self.assertEqual(s.build(u"hello joh\u0503n"), b"hello joh\xd4\x83n")
                                               ^
SyntaxError: invalid syntax

试图让它工作:

PY3 = sys.version_info[0] == 3
def u(s): return s if PY3 else s.decode("utf-8")

self.assertEqual(s.parse(b"hello joh\xd4\x83n"), u("hello joh\u0503n"))

引用自https://pythonhosted.org/six/

在 Python 2 上, u() 不知道文字的编码是什么。每个字节直接转换为相同值的 unicode 代码点。因此,只有将 u() 与 ASCII 数据字符串一起使用才是安全的。

但使用 unicode 的全部意义在于不限于 ASCII。

4

3 回答 3

1

您可以改为在任何地方from __future__ import unicode_literals使用而不使用该u语法吗?

from __future__ import unicode_literalsu使早期版本的 Python 中没有前面的字符串文字与 Python 3 中的一样,默认为 unicode。因此,如果您这样做from __future__ import unicode_literals并将 all 更改u"strings""strings",您的字符串文字在所有版本中都将是 unicode。这不会影响b文字。

于 2016-08-25T00:49:25.243 回答
1

我认为你在这里不走运。

使用six.u()或放弃对 Python 3.2 的支持。

于 2016-08-25T01:39:24.800 回答
0

我采取了执行six.u()并丢弃了six.

import sys
PY3 = sys.version_info[0] == 3
def u(s): return s if PY3 else unicode(s.replace(r'\\', r'\\\\'), "unicode_escape")
于 2016-08-25T12:27:08.063 回答