I'm running Python embedded in a C++ application. The program consists of a Qt GUI and a work QThread where computations happen. The user can chose to run a Python script from a file or to start a Python prompt. Both run in the QThread. The program exits when the python script is done or when we exit the python prompt. However, I want to handle the case when the user requests to quit from the GUI.
If running a Python script I can achieve this by a call to PyErr_SetInterrupt(see Stopping embedded Python). The Python interpreter stops, and we can quit normally. However, I haven't found a good way to force the Python prompt to quit.
I've tried feeding characters to stdin (with ungetc) in the hopes that the Python prompt receives them but without success. I do this from an overloaded PyOS_InputHook that I use to catch Qt events while the Python prompt is running.
Any ideas how to properly force the Python prompt to exit?
Can you not set up a slot receiver on your
QThreadsubclass that will callPyErr_SetInterruptin the proper context for you?You might achieve cleaner separation-of-concerns if, instead of using QThreads, you run your embedded Python interpreter in a separate process – which you can then
killit as you see fit, or at least you can if you’re on a POSIX-y platform; I take it this type of operation is way different on e.g. Windows.