Skip to content

Commit 8fecd92

Browse files
committed
Ensure single CPython interpreter per process
Introduces a _pythonInitialized flag to prevent repeated initialization and finalization of the CPython interpreter, addressing crashes on second launch with CPython 3.12. Py_Finalize is now commented out to maintain interpreter stability.
1 parent e3e46f9 commit 8fecd92

File tree

1 file changed

+12
-4
lines changed

1 file changed

+12
-4
lines changed

src/serious_python_android/lib/src/cpython.dart

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@ import 'gen.dart';
1111
export 'gen.dart';
1212

1313
CPython? _cpython;
14+
// Keep a single interpreter per process; repeated init/finalize of CPython 3.12
15+
// from an embedder is fragile and was crashing on second launch.
16+
bool _pythonInitialized = false;
1417

1518
CPython getCPython(String dynamicLibPath) {
1619
return _cpython ??= _cpython = CPython(DynamicLibrary.open(dynamicLibPath));
@@ -51,8 +54,13 @@ Future<String> runPythonProgramInIsolate(List<Object> arguments) async {
5154
debugPrint("programModuleName: $programModuleName");
5255

5356
final cpython = getCPython(dynamicLibPath);
54-
cpython.Py_Initialize();
55-
debugPrint("after Py_Initialize()");
57+
if (!_pythonInitialized) {
58+
cpython.Py_Initialize();
59+
_pythonInitialized = true;
60+
debugPrint("after Py_Initialize()");
61+
} else {
62+
debugPrint("Python already initialized; reusing interpreter");
63+
}
5664

5765
var result = "";
5866

@@ -75,8 +83,8 @@ Future<String> runPythonProgramInIsolate(List<Object> arguments) async {
7583
malloc.free(moduleNamePtr);
7684
}
7785

78-
cpython.Py_Finalize();
79-
debugPrint("after Py_Finalize()");
86+
// cpython.Py_Finalize();
87+
// debugPrint("after Py_Finalize()");
8088

8189
sendPort.send(result);
8290

0 commit comments

Comments
 (0)