Search code examples
pythonnumpyfortranf2py

How to end fortran function without error with f2py


I am writing a fortran function for python with f2py. Under a certain condition I would like to terminate the program and return my output without error. Unfortunately with stop the program stops with an error so that, when I call the function in python the whole script stops.

The way I do it now is to just put an conditional exit in the main loop of my function like this:

SUBROUTINE func(x)
...
do j1=1,N_steps

if (condition) then
 exit
end if

end do
end subroutine

The drawback however is that if the condition is not fulfilled it will check it on every iteration nontheless. Condition does not change in the loop. I would much prefer something like this

SUBROUTINE func(x)
...

if (condition) then
 stop
end if

do j1=1,N_steps
   ...
end do
end subroutine

but then the function does stop with an error.


Solution

  • I did not find a duplicate, so:

    You use the RETURN statement to return from a function or subroutine:

    if (condition)  return
    

    EXIT terminates a loop or other construct

    STOP terminates the whole program