简体   繁体   中英

How to interrupt python interpreter embedded in C++ application

We have a C++ QT application, we embedded python in it. We provided two interfaces to the user 1. Execute file 2. Stop execution. We execute a python file in a non GUI thread, using PyRun_FileExFlags. We would like to interrupt python file execution (assume python file has an infinite loop, it never completes execution). How to interrupt?

We tried following 1. In main thread set trace using PyEval_SetTrace 2. (if user click on Stop execution) In the trace call back function we set error "PyErr_SetString"

1:setting trace function

PyGILState_STATE state;
state = PyGILState_Ensure();                
PyEval_SetTrace(TraceHook, NULL);
PyGILState_Release(state);

2:trace function

int TraceHook(PyObject *obj, PyFrameObject *frame, int what, PyObject *arg)
{
if (b_isInterrupted)
{
PyGILState_STATE state;
state = PyGILState_Ensure();
PyErr_SetString(PyExc_KeyboardInterrupt, "Python Interrupted.");
PyGILState_Release(state);
}
return 0;
}

Python execution is not interrupted. I expect python execution to interrupt.

PyEval_SetTrace affects the current thread only.

You want PyErr_SetInterrupt . It interrupts (what Python considers to be) the main thread , regardless of the calling thread (which need not bother with the GIL).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM