问题描述
在 Windows 7 中使用 python 3.2 我在 IDLE 中得到以下信息:
Using python 3.2 in Windows 7 I am getting the following in IDLE:
>>compile('pass', r'c:\temp\工具\module1.py', 'exec')
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character
谁能解释为什么编译语句尝试使用 mbcs 转换 unicode 文件名?我知道 sys.getfilesystemencoding 在 Windows 中返回 'mbcs',但我认为在提供 unicode 文件名时不使用它.
Can anybody explain why the compile statement tries to convert the unicode filename using mbcs? I know that sys.getfilesystemencoding returns 'mbcs' in Windows, but I thought that this is not used when unicode file names are provided.
例如:
f = open(r'c:\temp\工具\module1.py')
有效.
要进行更完整的测试,请将以下内容保存在 utf8 编码文件中,并使用标准 python.exe 版本 3.2 运行它
For a more complete test save the following in a utf8 encoded file and run it using the standard python.exe version 3.2
# -*- coding: utf8 -*-
fname = r'c:\temp\工具\module1.py'
# I do have the a file named fname but you can comment out the following two lines
f = open(fname)
print('ok')
cmp = compile('pass', fname, 'exec')
print(cmp)
输出:
ok
Traceback (most recent call last):
File "module8.py", line 6, in <module>
cmp = compile('pass', fname, 'exec')
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: inval
id character
推荐答案
来自 Python 问题 10114,它似乎逻辑是 Python 使用的所有文件名都应该对使用它们的平台有效.它使用 Python 的 C 内部结构中使用的文件系统编码进行编码.
From Python issue 10114, it seems that the logic is that all filenames used by Python should be valid for the platform where they are used. It is encoded using the filesystem encoding to be used in the C internals of Python.
我同意它可能不应该在 Windows 上引发错误,因为任何 Unicode 文件名都是有效的.您可能希望为此使用 Python 提交错误报告.但请注意,必要的更改可能不是微不足道的,因为如果无法编码,任何使用文件名的 C 代码都必须做一些事情.
I agree that it probably shouldn't throw an error on Windows, because any Unicode filename is valid. You may wish to file a bug report with Python for this. But be aware that the necessary changes might not be trivial, because any C code using the filename has to have something to do if it can't be encoded.
这篇关于使用编译函数时的 UnicodeEncodeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!