Exceptions for Boost.Python and Python

How can I make boost.python code python error notifications?

For instance,

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

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

This is a toy example. My real problem is that I have a C function that can take several hours. And I want to interrupt it if it takes more than an hour, for example. But I do not want to kill the python instance, as part of the function was called.

Thanks in advance.

+4
source share
2 answers

In your C or C ++ code, install a signal handler for SIGINT, which sets a global flag, and your long-term function checks this flag periodically and returns earlier when the flag is set. Alternatively, instead of returning early, you can create a Python exception using the Python C API: see PyErr_SetInterrupt here .

+2
source

I'm not sure if boost.python has a solution - you may have to deal with it yourself. In this case, it is no different from conventional signal processing. A simple solution is to have a global variable that is changed by the signal handler and check this variable regularly . Another solution is to use setjmp / longjmp, but I think the first way is better when applicable, because it is simple and easy to maintain.

Please note that this is unix specific - I do not know how it works on Windows.

+2
source

Source: https://habr.com/ru/post/1286365/


All Articles