Re: [Numpy-discussion] error handling with f2py?

2009-01-16 Thread Pearu Peterson
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 modulenamemodule.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



___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


Re: [Numpy-discussion] error handling with f2py?

2009-01-16 Thread Sturla Molden
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 modulenamemodule.c file,
 for instance.

Thank you, Pearu :)

f2py is really a wonderful tool.


Sturla Molden
___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion


[Numpy-discussion] error handling with f2py?

2009-01-15 Thread Sturla Molden
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

___
Numpy-discussion mailing list
Numpy-discussion@scipy.org
http://projects.scipy.org/mailman/listinfo/numpy-discussion