If I embed the Python interpreter in a C or C++ program, as in this example, is there any way to limit how long the interpreter runs for? Is there anything to stop the Python co
I wanted to be able to interrupt any actively running Python code block, including cancelling an infinite loop or just some long-running code. In my application, single-threaded Python code is submitted and evaluated. An interrupt request can come at any time. This question and answer were crucial in helping me actually achieve that.
I use the middle approach from @Peter Brittain's answer from July 2016 above.
After I start the Python engine, I retrieve the thread id using the threading
package in Python code. I parse that into a c long value and save it.
The interrupt function is actually quite simple:
PyGILState_Ensure()
PyThreadState_SetAsyncExc(threadId, PyExc_Exception)
using the thread ID that I save from earlier and a generic exception type
PyGILState_Release()
So thank you to both the original question and to Peter Brittain!