如何在Python项目安装时自动编译Fortran源文件?
方法1:放弃Makefile,用setuptools+F2Py原生构建(推荐)
这种方式贴合Python打包规范,无需维护Makefile,由setuptools自动处理编译流程。
- 创建
pyproject.toml:声明构建依赖,确保安装时先获取编译所需工具
[build-system] requires = ["setuptools", "wheel", "numpy>=1.20"] build-backend = "setuptools.build_meta"
- 修改
setup.cfg:配置Fortran扩展模块
在setup.cfg中添加[options.ext_modules]段,指定Fortran源码、编译参数等:
[metadata] name = your-project-name version = 0.1.0 author = Your Name description = Python project with Fortran routines [options] packages = find: python_requires = >=3.8 install_requires = numpy>=1.20 [options.ext_modules] # 替换为你的模块名,比如myfortran_lib myfortran_lib = sources = src/module1.f90 src/module2.f90 # 你的Fortran源码路径 language = f90 # 指定语言为Fortran 90 extra_compile_args = -O3 -ffast-math # 自定义编译优化参数
- 验证安装
用户执行pip install .时,setuptools会自动调用F2Py编译Fortran源码,生成对应的.so文件并安装到Python环境中,无需手动执行make。
方法2:保留现有Makefile,让setuptools自动调用
如果不想修改现有Makefile,可以通过自定义构建命令让setuptools在安装时自动执行make。
- 创建
pyproject.toml:声明基础构建依赖
[build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta"
- 编写
setup.py:自定义构建扩展命令,调用Makefile
from setuptools import setup from setuptools.command.build_ext import build_ext import subprocess import os import shutil class AutoMakeBuild(build_ext): def run(self): # 在项目根目录执行make命令 root_dir = os.path.dirname(os.path.abspath(__file__)) subprocess.run(["make"], cwd=root_dir, check=True) # 将编译好的.so文件复制到Python包目录(替换为实际路径) so_file = os.path.join(root_dir, "myfortran.so") target_dir = os.path.join(root_dir, "myproject") if os.path.exists(so_file): shutil.copy(so_file, target_dir) else: raise FileNotFoundError(f"编译产物{so_file}未找到,请检查Makefile") # 执行默认构建流程 super().run() # 绑定自定义命令 setup(cmdclass={"build_ext": AutoMakeBuild})
- 修改
setup.cfg:配置项目元数据和包信息
[metadata] name = your-project-name version = 0.1.0 [options] packages = find: install_requires = numpy>=1.20
- 注意事项
- 确保Makefile生成的
.so文件名和路径正确,复制到Python包目录后才能被setuptools打包安装 - 需在项目文档中明确告知用户:需提前安装Fortran编译器(如
gfortran),否则编译会失败 - 可在
setup.py中添加编译器检查逻辑,提前抛出友好提示
通用注意事项
- 无论采用哪种方法,都要确保用户环境中有可用的Fortran编译器(GCC的gfortran、Intel的ifort等)
- 测试跨平台兼容性(Linux、macOS、Windows),Windows下可能需要配置MinGW或Intel Fortran环境
- 可通过
python -m pip install --no-build-isolation .测试构建流程,避免隔离环境带来的问题
内容的提问来源于stack exchange,提问作者L Maxime
相关产品推荐
相关产品推荐

