Tom*_*eus 7 python fortran f2py
我正在使用Fortran创建一个Python模块f2py
.如果在Fortran模块中遇到错误,我想在Python程序中产生错误(包括错误消息).请考虑以下示例:
Fortran代码(test.f):
subroutine foo(a,m)
integer :: m,i
integer, dimension(m) :: a
!f2py intent(in) :: m
!f2py intent(in,out) :: a
!f2py intent(hide), depend(a) :: m=shape(a)
do i = 1,m
if ( a(i) .eq. 0 ) then
print*, 'ERROR HERE..?'
end if
a(i) = a(i)+1
end do
end subroutine
Run Code Online (Sandbox Code Playgroud)
这个非常简单的程序增加1
了每个元素a
.但如果a(i)
等于零,应该产生错误.随附的Python代码:
import test
print test.foo(np.array([1,2],dtype='uint32'))
print test.foo(np.array([0,2],dtype='uint32'))
Run Code Online (Sandbox Code Playgroud)
输出现在是:
[2 3]
ERROR HERE..?
[1 3]
Run Code Online (Sandbox Code Playgroud)
但我希望Python程序能够抓住错误.请帮忙.
回答
stop
Fortran中的命令就是这样做的.考虑更新的Fortran代码:
subroutine foo(a,m)
integer :: m,i
integer, dimension(m) :: a
!f2py intent(in) :: m
!f2py intent(in,out) :: a
!f2py intent(hide), depend(a) :: m=shape(a)
do i = 1,m
if ( a(i) .eq. 0 ) then
print*, 'Error from Fortran'
stop
end if
a(i) = a(i)+1
end do
end subroutine
Run Code Online (Sandbox Code Playgroud)
输出现在是:
[2 3]
Error from Fortran
Run Code Online (Sandbox Code Playgroud)
即错误后Python代码不会继续.