Python error Unable to find vcvarsall.bat 错误是我在 Windows 平台下安装 Python 包时遇到的印象最深刻的问题。整理这篇解决方案的时间还在 2012 年 9 月 10 日。已经九年过去了,相信还有不少的朋友遇到类似的问题。抽空对先前的解决方案进行了重现梳理。主要变更是补充 Python 2 下的解决方案。
问题原因
你安装的包/模块中存在使用 cpython 写的内容,安装是需要将中间的 C 语言的代码编译成二进制文件后方可顺利完成安装。Windows 环境下默认的编译环境不支持上述编译操作。
解决方案
方案一:选择已经编译好 wheel 文件进行安装
准备工作:安装wheel 支持,pip install wheel
后续内容:寻找对应的 .whl 安装包(http://www.lfd.uci.edu/~gohlke/pythonlibs/)
安装方法:直接使用 pip install xxx.whl 进行安装,其中 xxx 为文件路径。
注意事项:
- 由于是非官方组织进行编译的,所以并不是所有包都有对应的二进制包
- 选择包时需要确定自己安装的 Python 的版本及安装的 Python 是 32 位的还是 64 位的
方案二:安装微软的编译环境 Visual Studio
Python 2.6 to 3.2
直接安装 Visual Studio 2008(测试过,安装完成直接可用,无需配置)或 Microsoft Visual C++ Compiler for Python 2.7(未测试)
Python 3.3 and 3.4
安装 Windows SDK for Windows 7 and .NET 4.0(未测试)或 Visual Studio 2010(安装后需要进行一些配置)
打开“<python 安装目录>\Lib\distutils\msvc9compiler.py”, 修改 msvc9compiler.py 文件,将:vc_env = query_vcvarsall(VERSION, plat_spec) 中的 VERSION 设定为已安装的 VS 版本对应的值:
- VS2008,则 VERSION 为 0
- VS2010,则 VERSION 为 0
- VS2012,则 VERSION 为 0
- VS2013,则 VERSION 为 0
- VS2014,则 VERSION 为 0
- …
Python 3.5 and later
Visual C++ Build Tools 2015(未测试)或 Visual Studio 2015
方案三:安装 MinGW 编译环境
由于安装 Visual Studio 太占空间了,个人更偏向安装 MinGW:
- 下载安装MinGW
- 在 MinGW 的安装目录下找到 bin 文件夹,找到 mingw32-make.exe,复制一份更名为 exe
- 把 MinGW 的路径添加到环境变量 path 中,比如我把 MinGW 安装到 D:\MinGW\中,就把 D:\MinGW\bin 添加到 path 中;
- 在 <python 安装目录>\distutils 增加文件 cfg,在文件里输入以下内容并保存
[build] compiler=mingw32
- 执行原先的模块安装,发现还是报错,报错内容为:error: command ‘gcc’ failed: No such file or directory 解决方案是将 D:\MinGW\lib 再添加到 PATH 中。
- 如果安装过程中出现 error: Could not find ‘openssl.exe’ 则直接到 https://pypi.org/project/pyOpenSSL/ 下载安装即可。
- 再次执行时安装模块时,发现如下错误:
D:\MinGW\bin\gcc.exe -mno-cygwin -mdll -O -Wall “-ID:\Program Files\Python27\include” “-ID:\Program Files\Python27\include” “-ID:\Program Files\Python27\PC” -c ../libdasm.c -o build\temp.win32-2.7\Release\..\libdasm.o cc1.exe: error: unrecognized command line option ‘-mno-cygwin’ error: command ‘gcc’ failed with exit status 1
原因是 gcc 4.6.x 以后不再接受 -mno-cygwin 为了解决这个问题需要修改 <python 安装目录>\distutils\cygwinccompiler.py 文件。找到:
self.set_executables(compiler='gcc -mno-cygwin -O -Wall', compiler_so='gcc -mno-cygwin -mdll -O -Wall', compiler_cxx='g++ -mno-cygwin -O -Wall', linker_exe='gcc', linker_so='%s -mno-cygwin %s %s' %(self.linker_dll, shared_option, entry_point))
修改为:
self.set_executables(compiler='gcc -O -Wall', compiler_so='gcc -mdll -O -Wall', compiler_cxx='g++ -mno-cygwin -O -Wall', linker_exe='gcc', linker_so='%s -mno-cygwin %s %s' %(self.linker_dll, shared_option, entry_point))
参考链接: