error handling with f2py?
![](https://secure.gravatar.com/avatar/86ea939a72cee216b3c076b52f48f338.jpg?s=120&d=mm&r=g)
Is it possible to make f2py raise an exception if a fortran routine signals an error? If I e.g. have subroutine foobar(a, ierr) Can I get an exception automatically raised if ierr != 0? Sturla Molden
![](https://secure.gravatar.com/avatar/2a726b0de1ade0be11fb5bc5a383d71d.jpg?s=120&d=mm&r=g)
On Thu, January 15, 2009 6:17 pm, Sturla Molden wrote:
Is it possible to make f2py raise an exception if a fortran routine signals an error?
If I e.g. have
subroutine foobar(a, ierr)
Can I get an exception automatically raised if ierr != 0?
Yes, for that you need to provide your own fortran call code using f2py callstatement construct. The initial fortran call code can be obtained from f2py generated <modulename>module.c file, for instance. An example follows below: Fortran file foo.f: ------------------- subroutine foo(a, ierr) integer a integer ierr if (a.gt.10) then ierr=2 else if (a.gt.5) then ierr=1 else ierr = 0 end if end if end Generated (f2py -m m foo.f) and then modified signature file m.pyf: ------------------------------------------------------------------- ! -*- f90 -*- ! Note: the context of this file is case sensitive. python module m ! in interface ! in :m subroutine foo(a,ierr) ! in :m:foo.f integer :: a integer :: ierr intent (in, out) a intent (hide) ierr callstatement ''' (*f2py_func)(&a, &ierr); if (ierr==1) { PyErr_SetString(PyExc_ValueError, "a is gt 5"); } if (ierr==2) { PyErr_SetString(PyExc_ValueError, "a is gt 10"); } ''' end subroutine foo end interface end python module m ! This file was auto-generated with f2py (version:2_5618). ! See http://cens.ioc.ee/projects/f2py2e/ Build the extension module and use from python: ----------------------------------------------- $ f2py -c m.pyf foo.f $ python
import m m.foo(30)
<type 'exceptions.ValueError'> Traceback (most recent call last) /home/pearu/test/f2py/exc/<ipython console> in <module>() <type 'exceptions.ValueError'>: a is gt 10
m.foo(6)
<type 'exceptions.ValueError'> Traceback (most recent call last) /home/pearu/test/f2py/exc/<ipython console> in <module>() <type 'exceptions.ValueError'>: a is gt 5
m.foo(4) 4
HTH, Pearu
![](https://secure.gravatar.com/avatar/86ea939a72cee216b3c076b52f48f338.jpg?s=120&d=mm&r=g)
On 1/16/2009 2:16 PM, Pearu Peterson wrote:
Yes, for that you need to provide your own fortran call code using f2py callstatement construct. The initial fortran call code can be obtained from f2py generated <modulename>module.c file, for instance.
Thank you, Pearu :) f2py is really a wonderful tool. Sturla Molden
participants (2)
-
Pearu Peterson
-
Sturla Molden