在setup.py中使用Unicode元数据的正确方法是什么?

时间:2009-07-21 23:43:54

标签: python unicode setuptools

我正在使用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 upload

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

python setup.py register

我通常通过运行'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("..."),
      ...)

有没有更好的方法?

3 个答案:

答案 0 :(得分:5)

这显然是在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

答案 1 :(得分: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

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

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

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

答案 2 :(得分:1)

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

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

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