help() 与 unicode __author__ 字符串
在 Python 2.6 脚本的开头,我想按照拼写写下我的名字,即“Joël”(e 上带有 trema)。所以我写了 __author__ = u'Joël'
,并且我可以通过简单的 print __author__
来检索它。
内置 help()
函数出现问题,因为我收到一条错误消息:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 2: ordinal not in range(128)
我无法升级到 Python 3.x,并且我发现这个函数非常有帮助(并且它肯定对那些谁会得到我的脚本)。我也没有忘记用 UTF-8 对文件进行编码,并通过添加以下内容在脚本中指定它:
# -*- coding: utf-8 -*-
知道它来自哪里吗?
预先感谢您的回答。
编辑 再次查看“Dive Into Python”一书,我发现如何在我的机器上进行正确的渲染,请参阅 http://www.diveintopython.org/xml_processing/unicode.html。
我的想法是,我的 Python 默认编码是 ASCII,这确实阻止了 help() 做出正确的输出。我所做的是在 {pythondir}\Lib\site-packages
中添加一个名为 sitecustomize.py
的脚本,设置默认编码:
import sys
sys.setdefaultencoding('iso-8859-1')
现在,使用输入字符串像u'Joël'
一样编写,我通过调用help()得到了正确的输出。
问题是,我很确定这会在其他计算机上崩溃。知道我该如何处理这个问题吗?
In the beginning of my scripts in Python 2.6, I would like to write my name as it is spelled, i.e. "Joël" (with trema on e). So I write __author__ = u'Joël'
, and I can retrieve it by a simple print __author__
.
Problem appears with the built-in help()
function, as I get an error message:
UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 2: ordinal not in range(128)
I cannot upgrade to Python 3.x, and I find this function very helpful (and it will surely be for those who will get my scripts). I also did not forget to encode the files in UTF-8, and to specify it in the scripts by adding this:
# -*- coding: utf-8 -*-
Any idea on where this comes from?
Thanks in advance for your answers.
EDIT
Looking to the "Dive Into Python" book again, I found out how to have a correct render on my machine, see http://www.diveintopython.org/xml_processing/unicode.html.
The idea is that, my default encoding for Python was ASCII, and this did prevent help() to make a correct output. What I did is to add a script named like sitecustomize.py
in {pythondir}\Lib\site-packages
, setting the default encoding:
import sys
sys.setdefaultencoding('iso-8859-1')
And now, with an input string written like u'Joël'
, I get a correct output through call of help().
Problem is, I'm quite sure that this will break on other's computers. Any idea how I could handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Pydoc 明确希望将作者姓名转换为 ascii:
您不太可能解决这个问题。
Pydoc explicitly wants to convert the author name to ascii:
It’s unlikely that you can work around this.
您需要使用简单字符串而不是 Unicode 字符串。因此:
内置的帮助方法会显示:
编辑:如果这不起作用,那么您可以通过执行以下操作强制返回您姓名的 8 位字符串版本:
You need to use a simple string and not a Unicode string. Therefore:
The built-in help method then displays:
Edit: If this doesn't work, then you can force returning a 8-bit string version of your name by doing this: