Search code examples
pythonfortranf2py

f2py a synnonym for the stop command


I have a fortran code called from python whenever it is needed. Sometimes an error is produced in the fortran computations and it is handled with the command STOP, which completely stops both fortran and python codes. However, I need python to continue running. Is there any other command that stopping the fortran code does not affect python?


Solution

  • In your case I would use some status variables and return, for subroutines this would look like

    subroutine mySqrt(number, res, stat)
      implicit none
      real,intent(in)     :: number
      real,intent(out)    :: res
      integer,intent(out) :: stat
    
      if ( number < 0.e0 ) then
        stat = -1 ! Some arbitrary number
        return    ! Exit
      endif
    
      res = sqrt(number)
      stat = 0
    end subroutine
    

    For functions this is a little difficult, but you could solve this by global (module) variables, but this is not thread-safe (in this version):

    module test
      integer,private :: lastSuccess
    contains
      function mySqrt(number)
        implicit none
        real,intent(in)     :: number
        real                :: mySqrt
    
        if ( number < 0.e0 ) then
          lastSuccess = -1 ! Some arbitrary number
          mySqrt = 0.      ! Set some values s.t. the function returns something
          return           ! Exit
        endif
    
        mySqrt = sqrt(number)
        lastSuccess = 0
      end function
    
      function checkRes()
        implicit none
        integer :: checkRes
    
        checkRes = lastSuccess
      end function
    end module test
    

    This way, you first evaluate the function, and then can check whether it succeeded, or not. No stop required. You could even work with different error codes.

    Another way (without internal variables) would be to set implausible results (like a negative number here), and check for that in your Python code.