Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access a function from FORTRAN which is writen in Python?

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

like image 664
Vincent Poirier Avatar asked Dec 29 '22 00:12

Vincent Poirier


2 Answers

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.

like image 94
S.Lott Avatar answered Dec 31 '22 15:12

S.Lott


@S.Lott's solution is the way to go. But to answer your question --- yes, it is possible to call Python from Fortran. I have done it by first exposing Python using Cython's C API, then creating Fortran interface to those C function using the iso_c_binding module, and finally calling them from Fortran. It's very heavyweight and in most practical problems not worthy (use the pipes approach), but it's doable (it worked for me).

like image 27
Ondřej Čertík Avatar answered Dec 31 '22 14:12

Ondřej Čertík