Me, blogging!

thoughts, science, code, jobs, and thoughts

f2py in action

Recently, I heavily made use of f2py—a tool that converts your FORTRAN code into a Python module. Here is how to use it:

$ f2py -c -m module_name fortran_code.f90

In the current directory there is now a shared object of your module To use it in Python, just do the usual import. A docstring is generated for you as well, so you know how to call the methods, i.e., FORTRAN subroutines or functions

import module_name as mymodule
print mymodule.__doc__

Let's suppose you've written a subroutine that does some calculations that are faster in FORTRAN than in Python

! fortran_code.f90
subroutine some_calulations(a,b,c)
  implicit none
  real, intent(in) :: a, b
  real, intent(out) :: c
  real :: some_result

  ! start some calculations
  c = some_result
end subroutine

To call that subroutine, our Python script has to look like this

import module_name as mymodule
print mymodule.__doc__

x1 = <some value>
x2 = <also some value>

result = mymodule.some_calculations(x1,x2)

That's it. Pretty easy, huh? Now you can use your fast code and let Python do the rest, like making a proper data analysis using numpy or scipy, or doing the graphics using matplotlib.

Tags: f2py, fortran, python, tools 2013/08/02
About Mario Krapp
I'm a physicist by training and graduated in Earth System Science.

And I like coding. I've been working with complex computer models ever since my undergrad and I enjoy data exploration and data analysis to gain insights into the underlying principles.

Feel free to contact me.