4

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.

1 Answer 1

3

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).

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

4 Comments

Thanks Davis, how to interrupt the thread (which is not main thread) which is executing PyRun_FileExFlags
@srinivasM: I don’t think Python knows more than what thread called Py_Initialize—can you arrange for it to be the same one?
Thanks @Davis: it worked for main thread. Can you suggest if there is a way to stop other threads?
@srinivasM: There is PyThreadState_SetAsyncExc, but I don’t know how to get its id argument.

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.