Search code examples
pythonfunctionrecover

How to reset Python interpreter to a 'safe' state?


I have a C++ app that embeds the Python interpreter. There are points in the code where the interpreter may get interrupted and I need to make sure the interpreter is in a 'safe' state to execute new code. I would just call Py_Finalize and re-initialize everything except I have a bunch of PyObject * references that I need to stay valid. Is there a function to do this or is it even necessary? When I mentioned the interpreter being interrupted above, I meant by a seg. fault or access violation which my app tries to recover from.


Solution

  • Er, trying to "recover" from a segfault or access violation is quite dangerous. There is a reason you get these in the first place, and it's that your program has tried to do something which it shouldn't have tried to do; therefore it has hit a bug or an unforeseen condition.

    There is no provision in the Python interpreter to roll back to a "safe point" in cases such as those mentioned. Even finalizing and reinitializing the interpreter might still leave some static data in a inconsistent state.

    If you told us why you are trying to do this we might be able to suggest an alternative.