views:

409

answers:

2

Hello!

How can I make boost.python code python exceptions aware?

For example,

int test_for(){
  for(;;){
  }
  return 0;
}

doesn't interrupt on Ctrl-C, if I export it to python. I think other exceptions won't work this way to.

This is a toy example. My real problem is that I have a C function that may take hours to compute. And I want to interrupt it, if it takes more that hour for example. But I don't want to kill python instance, within the function was called.

Thanks in advance.

+1  A: 

In your C or C++ code, install a signal handler for SIGINT that sets a global flag and have your long-running function check that flag periodically and return early when the flag is set. Alternatively, instead of an early return, you can raise a Python exception using the Python C API: see PyErr_SetInterrupt here.

Nathan Kitchen
The proper way to do this under Boost.Python is not to use the C API directly, but install an exception translator:register_exception_translator<RuntimeException>(my_runtime_exception_translator);voidmy_runtime_exception_translator(RuntimeException const}
Max Maximus
A: 

I am not sure boost.python has a solution - you may have to deal with this by yourself. In which case it is no different than conventional signal handling. The easy solution is to have a global variable which is changed by the signal handler, and to check this variable regularly. The other solution is to use setjmp/longjmp, but I think the first way is best when applicable, because it is simple and much more maintainable.

Note that this is unix specific - I don't know how this works on windows.

David Cournapeau