11

我正在使用 setuptools 为 Python 包编写 setup.py,并希望在 long_description 字段中包含一个非 ASCII 字符:

#!/usr/bin/env python
from setuptools import setup
setup(...
      long_description=u"...", # in real code this value is read from a text file
      ...)

不幸的是,将 unicode 对象传递给 setup() 会使用 UnicodeEncodeError 破坏以下两个命令中的任何一个

python setup.py --long-description | rst2html
python setup.py 上传

如果我对 long_description 字段使用原始 UTF-8 字符串,则以下命令会因 UnicodeDecodeError 中断:

python setup.py 注册

我通常通过运行“python setup.py sdist register upload”来发布软件,这意味着查看 sys.argv 并传递正确对象类型的丑陋黑客是正确的。

最后我放弃并实施了一个不同的丑陋黑客:

class UltraMagicString(object):
    # Catch-22:
    # - if I return Unicode, python setup.py --long-description as well
    #   as python setup.py upload fail with a UnicodeEncodeError
    # - if I return UTF-8 string, python setup.py sdist register
    #   fails with an UnicodeDecodeError

    def __init__(self, value):
        self.value = value

    def __str__(self):
        return self.value

    def __unicode__(self):
        return self.value.decode('UTF-8')

    def __add__(self, other):
        return UltraMagicString(self.value + str(other))

    def split(self, *args, **kw):
        return self.value.split(*args, **kw)

...

setup(...
      long_description=UltraMagicString("..."),
      ...)

没有更好的方法吗?

4

3 回答 3

6

这显然是已在 python 2.6 中修复的 distutils 错误:http: //mail.python.org/pipermail/distutils-sig/2009-September/013275.html

Tarek 建议修补 post_to_server。补丁应该预处理“data”参数中的所有值并将它们转换为unicode,然后调用原始方法。见http://mail.python.org/pipermail/distutils-sig/2009-September/013277.html

于 2009-09-17T13:51:15.673 回答
3
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from setuptools import setup
setup(name="fudz",
      description="fudzily",
      version="0.1",
      long_description=u"bläh bläh".encode("UTF-8"), # in real code this value is read from a text file
      py_modules=["fudz"],
      author="David Fraser",
      author_email="davidf@sjsoft.com",
      url="http://en.wikipedia.org/wiki/Fudz",
      )

我正在使用上面的代码进行测试---long-description 没有错误,只有 rst2html;上传似乎工作正常(尽管我实际上取消了上传)并且注册询问我我没有的用户名。但是您评论中的回溯很有帮助 - 这是导致问题unicode的命令中的自动转换。register

有关这方面的更多信息,请参阅illusive setdefaultencoding - 基本上,您希望 Python 中的默认编码能够将您的编码字符串转换回 unicode,但设置它很棘手。在这种情况下,我认为值得付出努力:

import sys
reload(sys).setdefaultencoding("UTF-8")

或者甚至是正确的,你可以从locale- 注释掉的代码中得到它/usr/lib/python2.6/site.py,你可以找到它,但我现在将离开那个讨论。

于 2009-07-24T15:29:14.710 回答
1

您需要将 unicode 长描述u"bläh bläh bläh"更改为普通字符串"bläh bläh bläh",并在文件的第二行添加编码头:

#!/usr/bin/env python
# encoding: utf-8
...
...

显然,您也需要使用 UTF-8 编码保存文件。

于 2009-07-25T15:02:47.717 回答