使用compile函数时的UnicodeEncodeError

时间:2012-01-10 04:31:43

标签: python windows unicode python-3.x

在Windows 7中使用python 3.2我在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文件名时不会使用它。

例如:

f = open(r'c:\temp\工具\module1.py') 

作品。

要进行更完整的测试,请将以下内容保存在utf8编码文件中,并使用标准python.exe版本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

3 个答案:

答案 0 :(得分:5)

Python issue 10114开始,似乎逻辑是Python使用的所有文件名应该对使用它们的平台有效。它使用文件系统编码进行编码,以便在Python的C内部使用。

我同意它可能不应该在Windows上抛出错误,因为任何Unicode文件名都是有效的。您可能希望使用Python提交错误报告。但请注意,必要的更改可能并不简单,因为如果无法编码,使用文件名的任何C代码都必须要做。

答案 1 :(得分:1)

这是一个适合我的解决方案:Issue 427: UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-6: ordinal not in range (128)

  

如果您在“编码的Python”主题中查看PyScripter帮助文件   源文件“(最后一段)它告诉你如何配置Python   通过修改site.py文件来支持其他编码。这个文件是   在Python安装目录的lib子目录中。找   函数setencoding并确保支持locale知道   默认字符串编码已启用。 (见下文)

def setencoding():
  """Set the string encoding used by the Unicode implementation.  The
  default is 'ascii', but if you're willing to experiment, you can
  change this."""
  encoding = "ascii" # Default value set by _PyUnicode_Init()
  if 0:  <<<--- set this to 1 ---------------------------------
      # Enable to support locale aware default string encodings.
      import locale
      loc = locale.getdefaultlocale ()
      if loc[1]:
          encoding = loc[1]
  if 0:
      # Enable to switch off string to Unicode coercion and implicit
      # Unicode to string conversion.
      encoding = "undefined"
  if encoding != "ascii":
      # On Non-Unicode builds this will raise an AttributeError...
      sys.setdefaultencoding (encoding) # Needs Python Unicode
build !

答案 2 :(得分:0)

我认为您可以尝试将文件路径中的“\”更改为“/”,就像

一样

compile('pass',r'c:\ temp \工具\ module1.py','exec')

compile('pass',r'c:/ temp /工具/module1.py','exec')

我遇到了和你一样的问题,我用这种方法来解决问题。我希望它能与你合作。