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

Mar*_*nas 9 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
      ...)
Run Code Online (Sandbox Code Playgroud)

不幸的是,将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("..."),
      ...)
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法?

Rei*_*ees 5

它显然是一个在python 2.6中修复的distutils bug:http://mail.python.org/pipermail/distutils-sig/2009-Stembert/013275.html

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