Calling Python from Fortran

Hello,

I have been learning Fortran for a few months now. Loving it so far: Fortran is much more modern and easy-to-use than I imagined.

Coming from Python, one of the main things I missed was matplotlib’s extensive visualisation capabilities. I found out about pyplot-fortran which builds Python scripts to display them. I have been using it a lot and loving the ease of use it provides. The main problem comes when trying to display large datasets, since it writes the whole data in the script itself. It made me wonder: how could you call Python from Fortran without making expensive copies?

By experimenting, I’ve built a small program that does that, using a C wrapper that can be called from Fortran using iso_c_binding and which starts a Python interpreter with the Fortran arrays as the data of NumPy arrays. Displaying the objects’ addresses shows that there is indeed no copy being made. I put the code on GitHub here.

As it took me a long while to get the whole machinery working, I’ve been wondering if there was an easier way to do this that I was missing.I know and have used tools like f2py to call Fortran from Python, but the reverse operation seems more difficult. Are some people here experienced with this kind of problem?

6 Likes

Hi, welcome to this Forum, and what an entrance! I will be giving this a go for defo.

1 Like

Hi and welcome! Awesome ! Thanks for sharing.

Neat. Thanks for sharing.

Here’s another implementation for calling Python from Fortran: GitHub - nbren12/call_py_fort: Call python from fortran · GitHub

And I’ll share some code I maintain which is specifically for plotting or other Python analysis from inside gdb: GitHub - mankoff/gdb_fortran_tools: Tools to help debug Fortran code with gdb - plotting, saving, and Numpy functions. · GitHub

4 Likes

There’s also the Forpy project. It works, I’ve used it.

Cheers.

1 Like