virtualenv创建Python虚拟环境时抛出UnicodeDecodeError异常的解决

  在通过pip安装TensorFlow时遇到了一个问题,当执行virtualenv --system-site-packages -p python ./venv创建新的虚拟环境时会抛出如下异常:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Traceback (most recent call last):
File "e:\python\lib\site-packages\virtualenv.py", line 939, in call_subprocess
line = line.decode(encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 38: invalid continuation byte

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "e:\python\lib\site-packages\virtualenv.py", line 2635, in <module>
main()
File "e:\python\lib\site-packages\virtualenv.py", line 870, in main
symlink=options.symlink,
File "e:\python\lib\site-packages\virtualenv.py", line 1173, in create_environment
install_wheel(to_install, py_executable, search_dirs, download=download)
File "e:\python\lib\site-packages\virtualenv.py", line 1019, in install_wheel
_install_wheel_with_search_dir(download, project_names, py_executable, search_dirs)
File "e:\python\lib\site-packages\virtualenv.py", line 1110, in _install_wheel_with_search_dir
call_subprocess(cmd, show_stdout=False, extra_env=env, stdin=script)
File "e:\python\lib\site-packages\virtualenv.py", line 941, in call_subprocess
line = line.decode(fs_encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xca in position 38: invalid continuation byte

  经过一番研究,原来出现异常的原因是调用decode()方法的errors参数为默认值"strict",即任何编码错误都会引发UnicodeDecodeError,将其更改为"ignore"即可忽略错误。具体修改如下:
  根据异常信息,将Python安装目录下的.\Lib\site-packages\virtualenv.py的第939行修改为line = line.decode(encoding, "ignore"),即增加一个"ignore"参数。
再次尝试创建虚拟环境,此时就不会抛出异常了:

1
2
3
4
5
6
Running virtualenv with interpreter E:\Python\python.exe
Already using interpreter E:\Python\python.exe
Using base prefix 'E:\\Python'
New python executable in D:\TensorFlow\venv\Scripts\python.exe
Installing setuptools, pip, wheel...
done.

  这时我们就拥有了一套独立的Python运行环境,不用担心污染主环境了