UnicodeEncodeError when using compilation function

Using python 3.2 on Windows 7, I get 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

Can someone explain why the compilation operator is trying to convert the file name to unicode using mbcs? I know that sys.getfilesystemencoding returns "mbcs" on Windows, but I thought it was not used when Unicode file names were specified.

eg:

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

work.

For a more complete test, save the following in a utf8 encoded file and run it using the standard version of 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)

Conclusion:

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
+5
source share
3 answers

Python issue 10114 , , , Python, , . , C- Python.

, , , Windows, Unicode . Python. , , C, , - , .

+5

, : 427: UnicodeEncodeError: ascii 1-6: (128):

PyScripter "Encoded Python " ( ), , Python , site.py. lib Python. setencoding , . (. )

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 !
+1

, "\" "/", ,

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

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

, , . , .

0
source

All Articles