Python库的路径存在中文路径引发的问题

open(fullname, “r”, encoding=‘utf-8’)
问题如下:

Failed to import the site module

Traceback (most recent call last):

  File "C:\Python36\lib\site.py", line 555, in

    main()

  File "C:\Python36\lib\site.py", line 542, in main

    known_paths = addsitepackages(known_paths)

  File "C:\Python36\lib\site.py", line 330, in addsitepackages

    addsitedir(sitedir, known_paths)

  File "C:\Python36\lib\site.py", line 209, in addsitedir

    addpackage(sitedir, name, known_paths)

  File "C:\Python36\lib\site.py", line 165, in addpackage

    for n, line in enumerate(f):

UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 136: illegal multibyte sequence

问题原因:C:\PythonXX\Lib\site-packages 目录下自定义的 XX.pth 文件中存在中文路径导致Python底层site文件读取时编码(默认CP936)异常

解决方法:修改 C:\PythonXX\lib\site.py 文件中第159行代码,在open中声明编码格式,如下:

try:
# f = open(fullname, "r")
f = open(fullname, "r", encoding='utf-8')
except OSError:
    return
with f:

说明:Python3组件的编码格式取决于:默认的(site-packages)、继承的(pth)、类库的(import)、函数的(encoding)几种方式。

你可能感兴趣的:(python)