目前,我的用户目录位于“C:\Users\João”,我正在运行 Windows 7 下的 Python 2.7 的 64 位版本。
通常情况下,Python 解释器默认编码为 'ascii'。然而,在 Eclipse 运行 Python 时,默认编码为 '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',我也不知道为什么。
那么这是什么原因呢?解决方法是什么?这是编程问题还是你认为可能是某些系统设置出了问题呢?
简而言之:在标准 Python 解释器中,主目录被正确报告为 'C:\Users\João',但在 Eclipse 中运行解释器时,则被报告为 'C:\Users\JoÆo'。为什么?