Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top