I am creating a Python module in Fortran using f2py
. I would like produce an error (including error message) in the Python program if an error is encountered in the Fortran module. Consider the following example:
Fortran code (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
This very simple program adds 1
to each element of a
. But should produce an error if a(i)
equal to zero. The accompanying Python code:
import test
print test.foo(np.array([1,2],dtype='uint32'))
print test.foo(np.array([0,2],dtype='uint32'))
The output is now:
[2 3]
ERROR HERE..?
[1 3]
But I want the Python program to hold on the error. Please help.
Answer
The stop
command in Fortran does exactly this. Consider the updated Fortran code:
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
The output is now:
[2 3]
Error from Fortran
I.e. the Python code does not continue after the error.