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
Don't waste a lot of time compiling and translating. Do this.
Fortran Part 1 program writes a file of stuff for Python to do. Write to stdout. Call this F1
Python reads a file, does the Python calculation, write the responses to a file for Fortran. Call this P.
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'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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With