Monday, January 10, 2011

Calling Fortran 90 from Python

I've been experimenting with calling Fortran 90 from Python. I've got an example working with gfortran 4.5.1 and python 2.6.6, here's how it works. First write the Fortran 90 code you'd like to call. In this example, I put the code in main.f90,

module main


subroutine print_int(a)
integer :: a
write(*,*) 'Hello from Fortran'
write(*,*) 'a = ', a
end subroutine print_int

subroutine print_mat_val( a )
integer :: a(0:2,0:2)
write(*,*) 'a(1,2) = ', a(1,2)
end subroutine print_mat_val

end module main

Next I create a shared object from this code using F2py, which is part of NumPy

f2py --fcompiler=gnu95 -c -m main main.f90

You can now import the module in Python. For example I create a file called with the following code,

import main
import numpy as np

a = np.array([[1,2,3],[4,5,6],[7,8,9]])


You can run the Python script by typing,


The calls contain main.main because both the file and the module are named 'main'. It isn't necessary to wrap the subroutines in a module, but it could be helpful for more complex code.