How can I access a function from FORTRAN that is written in Python?

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

I saw "f2py" which allows you to access the FORTRAN routine from Python and py2exe, which compiles the python script into an executable file. Is there anything for "py2f"? Is it possible to compile a Python script into an object file? Then I could associate it with the FORTRAN code.

For example, consider 'mypython_func.py' as a Python script containing a function and 'mainfortran.f' as the main FORTRAN code that 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 this possible?

Thanks for your time and help.

Vince

+4
source share
2 answers

Do not spend a lot of time collecting and translating. Do it.

  • Fortran Part 1 writes a file with files for Python. Write to stdout. Call this F1

  • Python reads the file, does Python calculate, writes file responses for Fortran. Name this P.

  • Fortran Part 2 reads a material file from stdin. These are the results of Python calculations.

Plug them

F1 | python p.py | F2 

You are not recompiling anything. Also note that all three start at the same time, which can be significant acceleration.

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 a function that reads stdin and writes stdout in Fortran format.

+6
source

@ The S.Lott solution is the way to go. But to answer your question --- yes, you can call Python from Fortran. I did this by first exposing Python using the Cython C API, and then creating a Fortran interface for these C functions using the iso_c_binding module and finally calling them from Fortran. It is very heavy and in most practical problems is not worthy (use the approach to pipes), but it is doable (it worked for me).

+4
source

Source: https://habr.com/ru/post/1302760/


All Articles