Stopping embedded Python

后端 未结 3 1361
无人及你
无人及你 2020-12-03 02:58

I\'m embedding Python interpreter to a C program. However, it might happen that while running some python script via PyRun_SimpleString() will run into infinite

3条回答
  •  猫巷女王i
    2020-12-03 03:28

    You can use Py_AddPendingCall() to add a function raising exception to be called on next check interval (see docs on sys.setcheckinterval() for more info). Here is an example with Py_Exit() call (which does works for me, but probably is not what you need), replace it with Py_Finalize() or one of PyErr_Set*():

    int quit(void *) {
        Py_Exit(0);
    }
    
    
    PyGILState_STATE state = PyGILState_Ensure();
    Py_AddPendingCall(&quit, NULL);
    PyGILState_Release(state);
    

    This should be enough for any pure-python code. But note, that some C functions can run for a while as a single operation (there was an example with long running regexp search, but I'm not sure it's still relevant).

提交回复
热议问题