[GRASS-dev] Emitting a Python exception instead of calling exit in GRASS

Sören Gebbert soerengebbert at googlemail.com
Sun Apr 22 10:37:26 EDT 2012


Dear devs,
while thinking about a high level Python interface based on the low
level ctypes interface a question raised in my mind:

Is it possible to raise a Python exception instead of calling exit in
case of a fatal error when using ctypes wrapped GRASS library
functions? So the calling module can gently exit, closing open
database connections and so on?

I am not a Python expert and know quite nothing about its C
implementation of exception handling,
but it seems to me that this will be quite hard to use in GRASS,
because it seems to me that Python C functions like
PyErr_SetString()[1]
simply set an error indicator which must be evaluated by the calling functions?

In the vtk-grass-bridge i am using setjmp/longjmp to shut down the
calling module gently in case of a fatall error. Does anybody know how
to do something similar with exceptions in the ctypes interface?
Something like a TRY/EXCEPT implementation in libgis using
setjmp/longjmp?

Untested and maybe wrong Example:

In libgis:
{{{
extern jmp_buf stack_buffer;
extern const char* error_message;

int TRY(){
    return !setjmp(stack_buffer);
}
}}}

The error function set with G_set_error_routine(error_handler):
{{{
static int error_handler(const char *msg, int fatal)
{
    if (fatal == 0)
    {
        fprintf(stderr, "%s\n", msg);
        return 1;
    }
    else
    {
        fprintf(stderr, "\n############## Exceptiont called ###########\n");
        error_message = msg;
        longjmp(stack_buffer, 1);
    }
    return 1;
}
}}}

Using this in Python:
{{{
import grass.lib.gis as libgis
import grass.lib.raster as libraster

if libgis.TRY():
    fd = libraster.Rast_open_old(name, mapset)
else:
    # Clean up
    # ...
    raise Exception(libgis.error_message)
}}}

does this makes any sense?


Thanks for any suggestions and best regards
Soeren


[1] http://docs.python.org/c-api/exceptions.html#PyErr_SetString


More information about the grass-dev mailing list