@@ -95,6 +95,7 @@ static mcmap_t mcmap = {
9595};
9696
9797static bool python_needs_shutdown = false ;
98+ static bool python_initialized = false ;
9899
99100int python_u_tld_key = -1 ;
100101int python_qobj_key = -1 ;
@@ -157,10 +158,12 @@ static void check_python_version() {
157158}
158159
159160static void python_module_shutdown () {
160- if (python_needs_shutdown ) {
161+ if (python_initialized ) {
161162 PyThreadState_Swap (nullptr );
162163 PyEval_AcquireThread (mainThreadState);
163164 _qore_PyGILState_SetThisThreadState (mainThreadState);
165+ }
166+ if (python_needs_shutdown) {
164167 int rc = Py_FinalizeEx ();
165168 if (rc) {
166169 printd (0 , " Unkown error shutting down Python: rc: %d\n " , rc);
@@ -233,12 +236,13 @@ static QoreStringNode* python_module_init_intern(bool repeat) {
233236 }
234237
235238 Py_InitializeEx (0 );
236- #ifndef QORE_ALLOW_PYTHON_SHUTDOWN
239+ #ifdef QORE_ALLOW_PYTHON_SHUTDOWN
237240 // issue# 4290: if we actively shut down Python on exit, then exit handlers in modules
238241 // (such as the h5py module in version 3.3.0) will cause a crash when the process exits,
239242 // as it requires the Python library to be still in place and initialized
240243 python_needs_shutdown = true ;
241244#endif
245+ python_initialized = true ;
242246 // printd(5, "python_module_init() Python initialized\n");
243247 }
244248
@@ -278,7 +282,7 @@ static QoreStringNode* python_module_init_intern(bool repeat) {
278282 }
279283
280284 mainThreadState = PyThreadState_Get ();
281- if (python_needs_shutdown ) {
285+ if (python_initialized ) {
282286 // release the current thread state after initialization
283287 PyEval_ReleaseThread (mainThreadState);
284288 assert (!_qore_PyRuntimeGILState_GetThreadState ());
0 commit comments