【发布时间】:2016-08-25 00:01:29
【问题描述】:
我有一连串在 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。
【问题讨论】:
-
是的,3.2 只是没有那种语法。您是否需要使用相同的代码库来支持 Python 2 和 Python 3.2,而不使用
2to3? -
@ArekBulski:2to3 永远不应该告诉你使用
six。我认为 2to3 中的任何代码都不知道six。当我使用u文字在代码上运行 2to3 时,它只会剥离u。
标签: python unicode travis-ci nose six