Skip to content

Commit 729bfba

Browse files
committed
Reset Python interpreter if already initialized
Instead of skipping initialization when the Python interpreter is already running, finalize the existing interpreter and reinitialize it. This ensures a fresh interpreter state and avoids issues with a potentially wedged event loop from previous sessions.
1 parent 26a728a commit 729bfba

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/serious_python_android/lib/src/cpython.dart

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -122,12 +122,14 @@ Future<String> runPythonProgramInIsolate(List<Object> arguments) async {
122122
cpython.Py_Initialize();
123123
_pyLog("after Py_Initialize()");
124124
} else {
125-
// Interpreter is already running; skip launching another run and let the
126-
// previously started script continue. Return a message for the caller.
127-
_pyLog("Python already initialized; skipping new run");
128-
final msg = "Python already initialized; skipped starting a new run.";
129-
sendPort.send(msg);
130-
return msg;
125+
// Interpreter was left running (likely from a previous app session). Tear
126+
// it down and start fresh to avoid reusing a wedged event loop.
127+
_pyLog("Python already initialized; finalizing stale interpreter");
128+
cpython.PyGILState_Ensure(); // ensure we own the GIL before finalizing
129+
cpython.Py_FinalizeEx();
130+
_pyLog("after Py_FinalizeEx(), reinitializing");
131+
cpython.Py_Initialize();
132+
_pyLog("after Py_Initialize() (fresh)");
131133
}
132134

133135
var result = "";

0 commit comments

Comments
 (0)