4

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
  • 1
    I'm interested in the answer to this. A simple and complete working example would be most helpful, if available. Commented Dec 30, 2011 at 2:03

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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); void my_runtime_exception_translator(RuntimeException const& ex) { PyErr_SetString(PyExc_RuntimeError, ex.toString().c_str()); }
Exception translators translate C++ exceptions to Python exceptions. I think the poster here wants the opposite: expose the KeyboardInterrupt python exception to C++.
I'm interested in this answer too. A minimal working example would be most helpful.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.