【发布时间】:2011-11-27 21:57:18
【问题描述】:
目前,我的用户目录位于“C:\Users\João”,我在 Windows 7 下运行 Python 2.7 的 64 位版本。
通常,Python 解释器以“ascii”作为默认编码运行。但是,由于某种原因,当 Eclipse 运行它时,默认编码是“utf-8”。现在,在常规 Python 控制台中,会发生以下情况:
>>> sys.getdefaultencoding()
'ascii'
>>> os.path.expanduser('~/filename')
'C:\\Users\\Jo\xe3o/filename'
>>> x = open(_, 'w')
>>> x.close()
>>>
我会注意到 '\xe3' 是 Latin-1 和 Windows-1252 中的 'ã' 的代码,并且一切正常。 但是,在 Eclipse 中,
>>> sys.getdefaultencoding()
'utf-8'
>>> os.path.expanduser('~/filename')
'C:\\Users\\Jo\xc6o/filename'
>>> x = open(_, 'w')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 13] Permission denied: 'C:\\Users\\Jo\xc6o/filename'
这令人困惑,因为 '\xc6' 是 'Æ' 的字符代码,而且它不是有效的 UTF-8。
如果您想知道“权限被拒绝”,而不是“没有这样的文件或目录”,有几个程序还向 'C:\Users\JoÆo' 写入了一些东西,我也不知道为什么。
那是什么原因造成的,解决办法呢?它甚至是程序性的,还是您认为可能是某些系统设置错误?
TL; DR:在标准 Python 解释器中,主目录被正确报告为“C:\Users\João”,而当解释器在 Eclipse 中运行时,主目录被正确报告为“C:\Users\JoÆo”。为什么?
【问题讨论】:
-
试试
os.path.expanduser(u'~/filename')(字符串前的u)......我不知道它是否会工作...... -
@Carpetsmoker 没有骰子。在控制台中,“UnicodeDecodeError:'ascii'编解码器无法解码位置 11 中的字节 0xe3:序数不在范围内(128)”。在 Eclipse 中,除了 'utf-8' 和 0xc6 以及原因“无效的连续字节”之外,相同。
标签: python windows eclipse internationalization pydev