【问题标题】:Missing u-strings on Python 3.2?Python 3.2 上缺少 u 字符串?
【发布时间】: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


【解决方案1】:

我认为你在这里不走运。

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

【讨论】:

【解决方案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 文字。

【讨论】:

  • 这个解决方案在 Travis 上失败了。
【解决方案3】:

我采取了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")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-26
    • 2021-10-16
    • 1970-01-01
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-08
    相关资源
    最近更新 更多