我有一长串在Travis CI上运行的单元测试,只有在PY3.2上它会失败。如何在不使用six.u()的情况下解决这个问题?
def test_parse_utf8(self):
s = String("foo", 12, encoding="utf8")
self.assertEqual(s.parse(b"hello johxd4x83n"), u"hello johu0503n")
======================================================================
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 johu0503n"), b"hello johxd4x83n")
^
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 johxd4x83n"), u("hello johu0503n"))
引自https://pythonhosted.org/six/
在Python 2上,u()不知道字面值的编码是什么。每个字节直接转换为相同的unicode码点价值。因此,只有对字符串使用u()才是安全的ASCII数据。
但是使用unicode的全部意义是不受限于ASCII。
我觉得你运气不好。
使用six.u()
或放弃Python 3.2的支持
你能代替from __future__ import unicode_literals
而不使用u
语法吗?
from __future__ import unicode_literals
使早期Python版本中没有前面u
的字符串字面量与Python 3中一样,这是默认的unicode。因此,如果执行from __future__ import unicode_literals
并将所有u"strings"
更改为"strings"
,则所有版本的字符串文字都将是unicode。这不会影响b
字面值
我取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")