The purpose of the F2PY –Fortran to Python interface generator– project is to provide a connection between Python and Fortran languages.

F2PY is a Python package (with a command line tool f2py and a module f2py2e) that facilitates creating/building Python C/API extension modules that make it possible to call Fortran 77/90/95 external subroutines and Fortran 90/95 module subroutines as well as C functions; to access Fortran 77 COMMON blocks and Fortran 90/95 module data, including allocatable arrays from Python.

For more information on the F2PY project, see http://www.f2py.com/.

The following variables are defined:

F2PY_EXECUTABLE      - absolute path to the F2PY executable
F2PY_VERSION_STRING  - the version of F2PY found
F2PY_VERSION_MAJOR   - the F2PY major version
F2PY_VERSION_MINOR   - the F2PY minor version
F2PY_VERSION_PATCH   - the F2PY patch version


By default, the module finds the F2PY program associated with the installed NumPy package.

Example usage

Assuming that a package named method is declared in setup.py and that the corresponding directory containing __init__.py also exists, the following CMake code can be added to method/CMakeLists.txt to ensure the C sources associated with cylinder_methods.f90 are generated and the corresponding module is compiled:

find_package(F2PY REQUIRED)

set(f2py_module_name "_cylinder_methods")
set(fortran_src_file "${CMAKE_CURRENT_SOURCE_DIR}/cylinder_methods.f90")

set(generated_module_file ${CMAKE_CURRENT_BINARY_DIR}/${f2py_module_name}${PYTHON_EXTENSION_MODULE_SUFFIX})

add_custom_target(${f2py_module_name} ALL
  DEPENDS ${generated_module_file}

  OUTPUT ${generated_module_file}
    -m ${f2py_module_name}

install(FILES ${generated_module_file} DESTINATION methods)


Using f2py with -c argument means that f2py is also responsible to build the module. In that case, CMake is not used to find the compiler and configure the associated build system.