2013-10-18 44 views
2

我有一个从python调用的fortran代码,只要需要它。有时在Fortran计算中会产生错误,并使用STOP命令处理,这会完全停止fortran和python代码。但是,我需要python继续运行。有没有其他命令停止Fortran代码不会影响python?f2py停止命令的同义词

回答

2

在你的情况我会使用一些状态变量和return,用于子程序这看起来像

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 

对于函数,这是一个有点困难,但你可以通过全局(模块)的变量解决这个问题,但这不是线程安全的(在这个版本):

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 

这样,你先评估函数,然后可以检查它是否成功,还是不行。否需要stop。你甚至可以使用不同的错误代码。

另一种方法(无内部变量)将设置不合理的结果(如负数),并检查你的Python代码。