Calling Fortran from Python

Robert Kern robert.kern at
Wed Apr 4 01:11:43 CEST 2007

Mangabasi wrote:

> Has anyone provide a similar example with Pyfort, F2Py or calldll?

With the latest f2py in numpy:

$ cat sample.pyf
!    -*- f90 -*-
! Note: the context of this file is case sensitive.

python module sample ! in
    interface  ! in :sample
        subroutine sample(ierr1,ierr2,ain,aout) ! in :sample:sample.f
            integer intent(out) :: ierr1
            integer intent(out) :: ierr2
            real*8 dimension(*),intent(in) :: ain

            !! This is what I had to modify from the generated interface. I
            !! changed 'dimension(*)' to 'dimension(len(ain))'.
            real*8 dimension(len(ain)),intent(out) :: aout
        end subroutine sample
    end interface
end python module sample

! This file was auto-generated with f2py (version:2_3582).
! See

]$ f2py -c -m sample  sample.pyf sample.f

running build
running config_fc
running build_src
building extension "sample" sources
creating /tmp/tmpZL8qAw
creating /tmp/tmpZL8qAw/src.macosx-10.3-fat-2.5
f2py options: []
f2py: sample.pyf
Reading fortran codes...
        Reading file 'sample.pyf' (format:free)
        Block: sample
                        Block: sample
Post-processing (stage 2)...
Building modules...
        Building module "sample"...
                Constructing wrapper function "sample"...
                  ierr1,ierr2,aout = sample(ain)
        Wrote C/API module "sample" to file
  adding '/tmp/tmpZL8qAw/src.macosx-10.3-fat-2.5/fortranobject.c' to sources.
  adding '/tmp/tmpZL8qAw/src.macosx-10.3-fat-2.5' to include_dirs.

... Etc.

$ ipython
Activating auto-logging. Current session state plus future input saved.
Filename       : /Users/rkern/.ipython/ipython.log
Mode           : backup
Output logging : False
Raw input log  : False
Timestamping   : False
State          : active

In [1]: import sample

In [2]: sample.sample([1, 2, 3])
Out[2]: (0, 0, array([ 4.,  6.,  0.]))

Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

More information about the Python-list mailing list