Windows下使用pip安装包出错

目录

Windows 使用 pip 安装 python 库时会出现如下的错误:

Exception:
Traceback (most recent call last):
  File "e:\tmp\python\env\lib\site-packages\pip\compat\__init__.py", line 73, in console_to_str
    return s.decode(sys.__stdout__.encoding)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 42: invalid start byte
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "e:\tmp\python\env\lib\site-packages\pip\basecommand.py", line 215, in main
    status = self.run(options, args)
  File "e:\tmp\python\env\lib\site-packages\pip\commands\install.py", line 342, in run
    prefix=options.prefix_path,
  File "e:\tmp\python\env\lib\site-packages\pip\req\req_set.py", line 784, in install
    **kwargs
  File "e:\tmp\python\env\lib\site-packages\pip\req\req_install.py", line 878, in install
    spinner=spinner,
  File "e:\tmp\python\env\lib\site-packages\pip\utils\__init__.py", line 676, in call_subprocess
    line = console_to_str(proc.stdout.readline())
  File "e:\tmp\python\env\lib\site-packages\pip\compat\__init__.py", line 75, in console_to_str
    return s.decode('utf_8')
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xa1 in position 42: invalid start byte

这是因为windows下使用的还是gbk编码,需要修改pip包下compat/__init__.py代码,大致在75行

if sys.version_info >= (3,):
    def console_to_str(s):
        try:
            return s.decode(sys.__stdout__.encoding)
        except UnicodeDecodeError:
            return s.decode('utf-8')

utf-8 改为 cp936,就可以正常使用 pip 安装了。