How to update python variables with f2py

77 views Asked by At

I'm trying to create a python program that uses fortran to do some calculations, but I'm struggling to update the variables values with the subroutines. To give a simple example of what I mean, I have a python script r.py:

import fortran_script
import numpy as np

a = np.array([10, 20, 30], np.float32)
b = 10
fortran_script.fmodule.r(a, b)
print(f"a = {a}")
print(f"b = {b}")

and a fortran script r.f90:

module fmodule
      implicit none
contains
      subroutine r(a, b)
      real, intent(inout):: a(:)
      integer, intent(inout) :: b
      a(1:3)=a(3:1:-1)
      b=b+10
      write(*,*) 'a = ', a
      write(*,*) 'b = ', b
      end subroutine r
end module fmodule

Compiling the fortran script with f2py and running the python code, the fortran writed the correct values:

 a =    30.0000000       20.0000000       10.0000000    
 b =           20

but python didn't get the correct values of the integer b:

a = [30. 20. 10.]
b = 10

So, my question is how do I properly pass and return values from a fortran subroutine to python with f2py?

1

There are 1 answers

1
Karthik On

you need to pass b also as a numpy array to get back its value.