F2PY - Fortran to Python interface generator

Author:: Pearu Peterson < pearu.peterson@gmail.com >

Introduction

F2PY is a tool that provides an easy connection between Python and Fortran languages. F2PY is part of NumPy.

F2PY creates extension modules from (handwritten or F2PY generated) signature files or directly from Fortran sources.

The generated extension modules facilitate:

In addition, F2PY can build the generated extension modules to shared libraries with only one command. F2PY uses the numpy.distutils module from NumPy that supports a number of major Fortran compilers. F2PY generated extension modules depend on NumPy that provides a fast multi-dimensional array language facility to Python. For building extension modules with Numeric or Numarray array backend, one can use the older and unmaintained version of F2PY: f2py2e.

Main features

Here follows a more detailed list of F2PY features:

The syntax of signature files is borrowed from the Fortran 90/95 language specification and has some F2PY specific extensions. The signature files can be modified to dictate how Fortran (or C) programs are called from Python:

Prerequisites

Since F2PY is a part of NumPy, the same prerequisites apply, that is, Python 2.3 or newer with distutils package must be installed.

Of course, to build extension modules, one also needs a working C and/or Fortran compilers installed.

Download and installation

Download and install NumPy in the usual way: python setup.py install.

Usage

To check if F2PY is installed correctly, run

f2py 

without any arguments. This should print out the usage information of the f2py program. To see which compilers are detected, run

f2py -c --help-fcompiler 

Next, try out the following three steps:

  1. Create a Fortran file hello.f that contains:

    • C File hello.f
            subroutine foo (a)
            integer a
            print*, "Hello from Fortran!"
            print*, "a=",a
            end
  2. Run
    • f2py -c -m hello hello.f

      This will build an extension module hello.so (or hello.sl, or hello.pyd, etc. depending on your platform) into the current directory.

  3. Now in Python try:
    • >>> import hello
      >>> print hello.__doc__
      >>> print hello.foo.__doc__
      >>> hello.foo(4)     
      Hello from Fortran!
      a= 4
      >>> 

Documentation

Future development

F2PY will be maintained and developed under the NumPy project.

A complete rewrite of F2PY is started to implement support for Fortran 90 derived types. See G3F2PY for more information about it.

F2py (last edited 2009-08-08 02:46:19 by mauro)