@@ -16,6 +16,10 @@ CPython getCPython(String dynamicLibPath) {
1616 return _cpython ?? = _cpython = CPython (DynamicLibrary .open (dynamicLibPath));
1717}
1818
19+ void _debug (String message) {
20+ debugPrint ("[serious_python] $message " );
21+ }
22+
1923Future <String > runPythonProgramFFI (bool sync , String dynamicLibPath,
2024 String pythonProgramPath, String script) async {
2125 final receivePort = ReceivePort ();
@@ -46,21 +50,24 @@ Future<String> runPythonProgramInIsolate(List<Object> arguments) async {
4650 var programDirPath = p.dirname (pythonProgramPath);
4751 var programModuleName = p.basenameWithoutExtension (pythonProgramPath);
4852
49- debugPrint ("dynamicLibPath: $dynamicLibPath " );
50- debugPrint ("programDirPath: $programDirPath " );
51- debugPrint ("programModuleName: $programModuleName " );
53+ _debug ("dynamicLibPath: $dynamicLibPath " );
54+ _debug ("programDirPath: $programDirPath " );
55+ _debug ("programModuleName: $programModuleName " );
5256
5357 final cpython = getCPython (dynamicLibPath);
54- cpython.Py_Initialize ();
55- debugPrint ("after Py_Initialize()" );
58+ if (cpython.Py_IsInitialized () == 0 ) {
59+ // Initialize the runtime only if it is not already active.
60+ cpython.Py_Initialize ();
61+ _debug ("after Py_Initialize()" );
62+ }
5663
5764 var result = "" ;
5865
5966 if (script != "" ) {
6067 // run script
6168 final scriptPtr = script.toNativeUtf8 ();
6269 int sr = cpython.PyRun_SimpleString (scriptPtr.cast <Char >());
63- debugPrint ("PyRun_SimpleString for script result: $sr " );
70+ _debug ("PyRun_SimpleString for script result: $sr " );
6471 malloc.free (scriptPtr);
6572 if (sr != 0 ) {
6673 result = getPythonError (cpython);
@@ -75,9 +82,6 @@ Future<String> runPythonProgramInIsolate(List<Object> arguments) async {
7582 malloc.free (moduleNamePtr);
7683 }
7784
78- cpython.Py_Finalize ();
79- debugPrint ("after Py_Finalize()" );
80-
8185 sendPort.send (result);
8286
8387 return result;
@@ -94,7 +98,7 @@ String getPythonError(CPython cpython) {
9498 cpython.Py_DecRef (tracebackModuleNamePtr.cast ());
9599
96100 if (tracebackModulePtr != nullptr) {
97- //debugPrint ("Traceback module loaded");
101+ //_debug ("Traceback module loaded");
98102
99103 final formatFuncName = "format_exception" .toNativeUtf8 ();
100104 final pFormatFunc = cpython.PyObject_GetAttrString (
0 commit comments