【问题标题】:Why is os.path.expanduser misbehaving when the home directory has special characters?当主目录有特殊字符时,为什么 os.path.expanduser 行为不端?
【发布时间】: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


【解决方案1】:

尝试更改 Eclipse 的默认编码。文件菜单:Windows --> 首选项;树栏:常规 -> 工作区;将“文本文件编码”从 Cp1252 更改为 ISO-8859-1。

如果您打开“调试配置”,转到“通用”选项卡,更改“编码”,也可以针对特定的调试配置进行更改。

编辑:很奇怪。在 64 位 Python 2.7.2、Windows 7 中,在 Eclipse 中使用 UTF-8 和 Cp1252(默认)在具有“João”目录的目录中对“./J*”执行 glob 对我来说效果很好。

UTF-8:

['.\Jo\xe3o']

CP1252:

['.\Jo\xe3o']

【讨论】:

    猜你喜欢
    • 2014-09-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-27
    相关资源
    最近更新 更多