编译f2py代码时遇vscvarsall.bat未找到错误,求解决方案
I’ve run into this exact issue before when working with f2py on Windows—let’s break down how to fix it step by step. The error pops up because Python’s distutils can’t locate the Visual Studio build environment it needs to compile the C wrapper code f2py generates, and you’ll also need a Fortran compiler since you’re working with f2py. Here’s what to do:
Step 1: Install the Right Visual Studio Build Tools
Python 3.6 on Windows relies on either Visual Studio 2015 or 2017 Build Tools (newer versions like VS2019/2022 might not play nice without extra configuration).
- Grab the VS2017 Build Tools installer (it’s still available via Microsoft’s official downloads).
- When you run the installer, make sure to check the "Visual C++ build tools" workload—this includes the missing
vscvarsall.batfile and all the C compilation tools Python needs. Don’t skip the Windows SDK component that matches your Windows 10 version either; it’s required for system-level builds.
Step 2: Add a Fortran Compiler (Critical for f2py)
f2py needs a Fortran compiler to process your Fortran code—you’ve got two solid options:
- Intel Fortran Compiler: If you have access to it, install a version compatible with your Visual Studio build tools. Make sure it integrates with VS during installation so f2py can pick it up automatically.
- MinGW-w64: A free, open-source alternative. Install the 64-bit version, and during setup, select the Fortran compiler option. After installing, add the MinGW
binfolder (usually something likeC:\mingw64\bin) to your system’sPATHenvironment variable so Python can find it.
Step 3: Configure Python to Use the Compilers
Once the tools are installed, you need to make sure Python can access them:
- For Visual Studio: Instead of using a regular Command Prompt, open the Developer Command Prompt for Visual Studio (you’ll find it in the Start Menu under your Visual Studio folder). Run your
build_f2py_modules.pyscript from this prompt—it automatically sets up all the environment variables thatdistutilsneeds to findvscvarsall.bat. - For MinGW: Create a file named
distutils.cfgin your Python’sLib\distutilsdirectory (e.g.,C:\Python36\Lib\distutils) and add these lines:
If you get an error saying[build] compiler = mingw32mingw32isn’t recognized, double-check that MinGW’sbinfolder is in yourPATHand that you installed the Fortran component correctly.
Step 4: Test Your Setup
To confirm everything’s working, try a quick test. Create a tiny Fortran file called test.f90:
subroutine hello print *, 'Hello from Fortran!' end subroutine hello
Then run this command in your prompt:
f2py -c test.f90 -m test
If you get a .pyd file without errors, your setup is good to go—you can now run your original build_f2py_modules.py script successfully.
内容的提问来源于stack exchange,提问作者Tom Heeley

