views:

93

answers:

1

Hi,

Is there any way to use a python function in FORTRAN? I was given a python script that contains some functions and I need to access this function from a FORTRAN code.

I've seen 'f2py' which allows a FORTRAN subroutine to be accessed from Python, and py2exe which will compile python script to an executable. Is there anything out there for 'py2f'? Can a Python script be compiled to an object file? Then I could link it with the FORTRAN code.

For example consider 'mypython_func.py' as a Python script containing a function and 'mainfortran.f' as the main program FORTRAN code which calls the Python function. I would like to: from 'mypython_func.py' compile to 'mypython_func.o', from 'mainfortran.f' compile to 'mainfortran.o' (>> gfortran -c mainfortran.f), then link these files (>> gfortran -c mainfortran.o mypython_func.o -o myexec.exe). Is anything like this possible?

Thank you for your time and help.

Vince

+1  A: 

Don't waste a lot of time compiling and translating. Do this.

  1. Fortran Part 1 program writes a file of stuff for Python to do. Write to stdout. Call this F1

  2. Python reads a file, does the Python calculation, write the responses to a file for Fortran. Call this P.

  3. Fortran Part 2 program reads a file of stuff from stdin. These are the results of the Python calculations.

Connect them

F1 | python p.py | F2

You don't recompile anything. Also note that all three run concurrently, which may be a considerable speedup.

The middle bit of Python should be something like this.

import sys
import my_python_module
for line in sys.stdin:
    x, y, p, q = map( float, line.split() )
    print ("%8.3f"*6) % ( x, y, z, p, q, my_python_module.some_function( x, y, p, q ) )

A simple wrapper around the function that reads stdin and writes stdout in a Fortran-friendly format.

S.Lott
Great, I'll give that a try. Thank you.
Vincent Poirier