Created
January 10, 2025 07:33
-
-
Save krystophny/7a0e15050b3575dbac2054af62e7fccb to your computer and use it in GitHub Desktop.
setup.py for f2py with legacy support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from setuptools import Extension, setup | |
from setuptools.command.build_ext import build_ext | |
from importlib.machinery import EXTENSION_SUFFIXES | |
import os | |
import shutil | |
import sys | |
import subprocess | |
import sysconfig | |
class F2PyExtension(Extension): | |
def __init__(self, name, fortran_sources, **kwargs): | |
super().__init__(name, sources=[], **kwargs) | |
self.fortran_sources = fortran_sources | |
class BuildF2PyExtension(build_ext): | |
def build_extension(self, ext): | |
output_module = ext.name | |
env = os.environ.copy() | |
if sys.version_info < (3, 12): | |
env["SETUPTOOLS_USE_DISTUTILS"] = "1" | |
subprocess.check_call([ | |
"f2py", "-c", "-m", output_module, *ext.fortran_sources | |
], env=env) | |
ext_suffix = sysconfig.get_config_var("EXT_SUFFIX") | |
lib_name = f"{output_module}{ext_suffix}" | |
ext_path = self.get_ext_fullpath(ext.name) | |
ext_dir = os.path.dirname(ext_path) | |
if not os.path.exists(ext_dir): | |
os.makedirs(ext_dir) | |
shutil.move(lib_name, ext_path) | |
ext = F2PyExtension('my_ext', | |
fortran_sources=['source1.f90', | |
'source2.f90']) | |
setup( | |
ext_modules=[ext], | |
cmdclass={'build_ext': BuildF2PyExtension}, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this simple environment variable fix. It's mind-boggling that these so-called professionals just tell you to 'stop doing things the old way.'