【问题标题】:UnicodeError error when calling Django i18n makemessages command调用 Django i18n makemessages 命令时出现 UnicodeError 错误
【发布时间】:2017-04-05 02:48:15
【问题描述】:

我正在使用 Django 的国际化功能为 web 应用程序生成翻译字符串。

我尝试调用makemessages 时出现问题,而现有语言.po 文件包含特殊字符(例如$£ 等)。

如果其中之一存在,makemessages 会尝试加载现有的.po 文件并对其进行解码。当它这样做时,我得到一个错误:

Traceback (most recent call last):
 File "manage.py", line 18, in <module>
   execute_from_command_line(sys.argv)
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line
   utility.execute()
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 346, in execute
   self.fetch_command(subcommand).run_from_argv(self.argv)
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 394, in run_from_argv
   self.execute(*args, **cmd_options)
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 445, in execute
   output = self.handle(*args, **options)
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 325, in handle
   self.write_po_file(potfile, locale)
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 458, in write_po_file
   msgs, errors, status = gettext_popen_wrapper(args)
 File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/makemessages.py", line 51, in gettext_popen_wrapper
   stdout = stdout.decode(stdout_encoding)
 File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode
   return codecs.utf_8_decode(input, errors, True)
UnicodeEncodeError: 'ascii' codec can't encode character u'\xa2' in position 2105: ordinal not in range(128)

我试图在这里追溯回溯,但我不知道发生了什么。

似乎 Django 尝试将现有的 .po 文件解码为 UTF8,但是在重新编码时,它使用的是 ASCII 编解码器。

我们将不胜感激任何有关问题所在的见解。


编辑:

  • 操作系统:Ubuntu 15.10 和 OS X 10.11.6
  • Python:2.7.10 和 2.7.11
  • Django:1.8.14
  • 六:1.10.0

我已尝试按照建议重新安装 Django/Six,但错误仍然存​​在。

Ubuntu 的localedef --list-archive:

en_AG
en_AG.utf8
en_AU.utf8
en_BW.utf8
en_CA.utf8
en_DK.utf8
en_GB.utf8
en_HK.utf8
en_IE.utf8
en_IN
en_IN.utf8
en_NG
en_NG.utf8
en_NZ.utf8
en_PH.utf8
en_SG.utf8
en_US.utf8
en_ZA.utf8
en_ZM
en_ZM.utf8
en_ZW.utf8

有问题的翻译文件的内容类型:

 "Content-Type: text/plain; charset=UTF-8\n"

【问题讨论】:

  • 试试这个:LC_CTYPE=en_US.UTF-8 python manage.py makemessages;有用吗?
  • @nobe4:使用LC_CTYPE=en_US.UTF-8 python manage.py makemessages 运行它会有所不同吗?还有,顺便说一句,你的操作系统和版本是什么?
  • @AntonisChristofides:抱歉耽搁了,这个命令不能解决问题。我已详细更新了我的问题。
  • 你能显示localedef --list-archive的输出吗?这将适用于 Ubuntu;我不确定 Mac OS X。

标签: python django utf-8 translation


【解决方案1】:

请注意,这是与 cmets 中提到的 this similar question 不同的异常位置。

在我看来,发生这种情况的唯一方法是,如果对 django 安装进行了修改,或者在 python 2.7 版本中存在错误。

你的堆栈是:

> msgs, errors, status = gettext_popen_wrapper(args)
> stdout = stdout.decode(stdout_encoding)

gettext_popen_wrapper(在 django 1.8 上,我认为您正在使用,您能确认一下吗?)和 popen_wrapper 创建 stdout(在删除 cmets/docstrings 并重新缩进之后为清楚起见,请参阅 github 上的 popen_wrappergettext_popen_wrapper 以获得纯正代码):

def popen_wrapper(args, os_err_exc_type=CommandError, universal_newlines=True):
    try:
        p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE,
                close_fds=os.name != 'nt', universal_newlines=universal_newlines)
    except OSError as e:
        strerror = force_text(e.strerror, DEFAULT_LOCALE_ENCODING,
                              strings_only=True)
        six.reraise(os_err_exc_type, os_err_exc_type('Error executing %s: %s' %
                    (args[0], strerror)), sys.exc_info()[2])
    # NB: subprocess.Popen.communicate() should return two bytes 
    # (i.e. str in python 2) objects
    output, errors = p.communicate()
    return (
        output,
        force_text(errors, DEFAULT_LOCALE_ENCODING, strings_only=True),
        p.returncode
    )

def gettext_popen_wrapper(args, 
                          os_err_exc_type=CommandError, 
                          stdout_encoding="utf-8"):
    manual_io_wrapper = six.PY3 and stdout_encoding != DEFAULT_LOCALE_ENCODING

    stdout, stderr, status_code = popen_wrapper(
        args, os_err_exc_type=os_err_exc_type,
        universal_newlines=not manual_io_wrapper)

    if manual_io_wrapper:
        stdout = io.TextIOWrapper(io.BytesIO(stdout), encoding=stdout_encoding).read()
    if six.PY2:
        # EXCEPTION HIT ON THE FOLLOWING LINE
        stdout = stdout.decode(stdout_encoding)
    return stdout, stderr, status_code

所以当我们调用stdout.decode() 时,stdout 应该是一个普通的str 对象(即一堆需要解码的字节)。但是,如果是这种情况,那么为什么zh编码会出现异常?我们只需要在对象已经是 unicode 对象时进行编码,即如果它是 unicode 类型。果然,如果我们添加这一行

stdout = stdout.decode('utf-8')

之前

stdout = stdout.decode(stdout_encoding)

那么现在decode 方法首先尝试使用default encoding of asciiencode unicode stdout,这会导致您看到的异常。通过将manual_io_wrapper 设置为True,我也遇到了同样的错误,这导致stdout = io.TextWrapper(...) 行也发生(这也会产生一个unicode),但这不应该是True,因为你在python 2 不是 3。

所以我认为:

  • 您安装了错误的djangosix,或者它已被编辑。尝试重新安装它们。
  • 您在subprocess.Popen.communicate() 中遇到了一个错误,并且由于某种原因它返回了unicode 而不是str(我相信如果universal_newlines are turned on 是可能的python 3。您可以通过重新安装python 或升级到更高版本。

我的主要观点是,我认为这不是环境问题。了解任何后续行动都会很有趣:

  • 你在什么平台上
  • 你使用的是什么 python 2.7
  • 您使用的是什么 django。

【讨论】:

    【解决方案2】:

    在下一行,不知何故,stdout 不是字节str,而是它的unicode,并且您在隐式编码该unicode 期间遇到异常。

    stdout = stdout.decode('utf-8')
    

    这是因为decode() 应该在字节str 上执行,当我们尝试在unicode 上调用decode 时,在python 2.7 中,将隐含调用encode 与@ 987654331@ 在decode 之前,对encode 的调用将使用默认的charset,即python 中的ascii

    unicode.encode() --> byte   # results in str
    byte.decode() --> unicode   # results in unicode
    unicode.decode() --> unicode.encode().decode()  # implicit encode call
    

    所以,开始调查导致 stdout 为 unicode 的原因。

    谢谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多