PyThreadState * Py_NewInterpreter(void) { PyInterpreterState *interp; PyThreadState *tstate, *save_tstate; PyObject *bimod, *sysmod; if (!initialized) Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); interp = PyInterpreterState_New(); if (interp == NULL) return NULL; tstate = PyThreadState_New(interp); if (tstate == NULL) { PyInterpreterState_Delete(interp); return NULL; } save_tstate = PyThreadState_Swap(tstate); /* XXX The following is lax in error checking */ interp->modules = PyDict_New(); bimod = _PyImport_FindExtension("__builtin__", "__builtin__"); if (bimod != NULL) { interp->builtins = PyModule_GetDict(bimod); Py_INCREF(interp->builtins); } sysmod = _PyImport_FindExtension("sys", "sys"); if (bimod != NULL && sysmod != NULL) { interp->sysdict = PyModule_GetDict(sysmod); Py_INCREF(interp->sysdict); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); initmain(); if (!Py_NoSiteFlag) initsite(); } if (!PyErr_Occurred()) return tstate; /* Oops, it didn't work. Undo it all. */ PyErr_Print(); PyThreadState_Clear(tstate); PyThreadState_Swap(save_tstate); PyThreadState_Delete(tstate); PyInterpreterState_Delete(interp); return NULL; }
void PythonFlowAnalyzer::performStart() { Py_Initialize(); PyObject* m = PyImport_AddModule("__main__"); if (!m) { PyErr_Print(); THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code (1)"); } PyRun_SimpleString("import sys; sys.path.append('.')\n"); msg(MSG_ERROR, "PYTHONPATH=%s", Py_GetPath()); PyObject* pymodule = PyImport_ImportModule("PythonFlowAnalyzer"); if (!pymodule) { PyErr_Print(); THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code (2.5)"); } pyDict = PyModule_GetDict(pymodule); if (!pyDict) { PyErr_Print(); THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code (2)"); } PyObject* env = PyRun_String(code.c_str(), Py_file_input, pyDict, pyDict); if (!env) { PyErr_Print(); THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code (3)"); } pyClass = PyDict_GetItemString(pyDict, "FlowRecord"); if (!pyClass) { PyErr_Print(); THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code (3.5)"); } PyObject* pyclass = PyDict_GetItemString(pyDict, "FlowAnalyzer"); if (!pyclass) { PyErr_Print(); THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code (4)"); } PyObject* pyinstance = PyObject_CallObject(pyclass, NULL); if (!pyinstance) { PyErr_Print(); THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code (5)"); } //PyObject_Print(pyinstance, stdout, 0); pyFunc = PyObject_GetAttrString(pyinstance, "onDataRecord"); if (!pyFunc) { PyErr_Print(); THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code, function 'onDataRecord' not found"); } if (!PyCallable_Check(pyFunc)) { THROWEXCEPTION("PythonFlowAnalyzer: failed to execute given Python code, function 'onDataRecord' is not callable"); } }
const bool PythonScript::import() { // Opens the script's source file. std::string source; bool result = vgio::readFile(m_filename.string(), source); if( !result ) { qDebug() << "Error opening file: " << m_filename.c_str(); QMessageBox::information(0, "Script loading error", QString()); return false; } // Compiles the code from the given python source file and create the associated module. PyObject * code = 0; code = Py_CompileString( source.c_str(), m_filename.string().c_str(), Py_file_input ); if( !code ) { PyErr_Print(); QMessageBox::warning( 0, "Script error", "An error has occured while load the script. Please see the console for additional details." ); return false; } m_pyModule = PyImport_ExecCodeModule( "script", code ) ; Py_DECREF(code); // References the module of the script module in the __main___ module for later use. PyObject * mainModule = PyImport_AddModule("__main__"); PyObject * mainDict = PyModule_GetDict(mainModule); PyDict_SetItemString(mainDict, "script", m_pyModule); // Adds . in sys.path on posix platform #ifndef WIN32 std::string path = Py_GetPath(); path = ":" + path; PySys_SetPath( path.c_str() ); #endif // Import vgsdk libraries PyObject * scriptDict = PyModule_GetDict(m_pyModule); PyObject * vgdModule = PyImport_ImportModule("vgd"); PyDict_SetItemString(scriptDict, "vgd", vgdModule); PyObject * vgmModule = PyImport_ImportModule("vgm"); PyDict_SetItemString(scriptDict, "vgm", vgmModule); PyObject * vgeModule = PyImport_ImportModule("vge"); PyDict_SetItemString(scriptDict, "vge", vgeModule); PyObject * vgUIModule = PyImport_ImportModule("vgUI"); PyDict_SetItemString(scriptDict, "vgUI", vgUIModule); // Job's done. return true; }
void PythonModule::Initialize() { // internal output must be created before python inits InternalOutput::GetReference(); // tells python where to look for its 'lib' files Py_NoSiteFlag=1; Py_SetPythonHome(L"../Python/."); Py_Initialize(); // tell python where to search for modules std::wstring new_path = Py_GetPath(); new_path += L";../Scripts"; PySys_SetPath(new_path.c_str()); }
static void load_config(struct global *global) { const char *filename; GDir *dir; char *mypath = g_build_filename(global->config->config_dir, "python", NULL); char *oldpath, *newpath; g_mkdir_with_parents(mypath, 0755); oldpath = Py_GetPath(); newpath = g_strdup_printf("%s:%s", mypath, oldpath); PySys_SetPath(newpath); g_free(newpath); dir = g_dir_open(mypath, 0, NULL); if (!dir) { log_global(LOG_WARNING, "Unable to open `%s'", mypath); g_free(mypath); return; } g_free(mypath); while ((filename = g_dir_read_name(dir))) { char *modulename; if (strcmp(filename + strlen(filename)-3, ".py") != 0) continue; modulename = g_strndup(filename, strlen(filename)-3); log_global(LOG_TRACE, "Loading python plugin `%s'", modulename); if (PyImport_ImportModule(modulename) == NULL) { PyErr_Print(); PyErr_Clear(); } } g_dir_close(dir); }
static void api_load_module(int argc, char* argv[]) { PyObject *pName; // Attempt to initialize the Python interpreter. Py_SetProgramName(argv[0]); Py_Initialize(); PySys_SetArgv(argc, argv); // Load the extension module. initsvmapi(); pExtModule = PyImport_AddModule(SVMAPINAME); // Get the name of the module. // First try the --m option... char *moduleName = NULL; int i; for (i=0; i<argc; ++i) if (!strcmp("--m", argv[i])) break; if (i<argc-1) moduleName = argv[i+1]; // Next try the environment variable SVMPYTHON_MODULE. if (moduleName == NULL) moduleName = getenv("SVMPYTHON_MODULE"); // Next just use the default module defined at build time. if (moduleName == NULL) moduleName = STRINGIFY(DEFAULT_MODULE); // Attempt to load the user module. pName = PyString_FromString(moduleName); pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule == NULL) { // If we could not load the module, output some helpful diagnostic output. fprintf(stderr, "COULD NOT LOAD MODULE \"%s\"!\n", moduleName); fprintf(stderr, "perhaps module is not in module search path?\n"); fprintf(stderr, "path is: %s\n", Py_GetPath()); Py_Exit(1); } svmapi_usermodule = pModule; }
int start (int argc, char **argv) { int rc; PyObject *new_path; PySys_SetArgv(argc, argv); // PySys_SetArgv munged the path - specifically, it added the // directory of argv[0] at the start of sys.path. // Create a new list object for the path, and rely on our // implementation knowledge of set_path above, which writes into // the static Py_GetPath() buffer (Note: Py_GetPath() does *not* // return the current sys.path value - its just a static buffer // holding the initial Python paths) new_path = PyList_New(1); if (new_path) { PyObject *entry = PyString_FromString(Py_GetPath()); if (entry && (0==PyList_SetItem(new_path, 0, entry))) PySys_SetObject("path", new_path); Py_DECREF(new_path); } rc = run_script(); fini(); return rc; }
// Set the Python path before initialization static int set_path_early() { char *ppath; Py_SetPythonHome(libdirname); /* Let Python calculate its initial path, according to the builtin rules */ ppath = Py_GetPath(); // printf("Initial path: %s\n", ppath); /* We know that Py_GetPath points to writeable memory, so we copy our own path into it. */ if (strlen(ppath) <= strlen(libdirname) + strlen(pZipBaseName) + 1) { /* Um. Not enough space. What now? */ SystemError(0, "Not enough space for new sys.path"); return -1; } strcpy(ppath, libdirname); strcat(ppath, "\\"); strcat(ppath, pZipBaseName); return 0; }
/* * Class: org_jpy_PyLib * Method: startPython0 * Signature: ([Ljava/lang/String;)Z */ JNIEXPORT jboolean JNICALL Java_org_jpy_PyLib_startPython0 (JNIEnv* jenv, jclass jLibClass, jobjectArray jPathArray) { int pyInit = Py_IsInitialized(); JPy_DIAG_PRINT(JPy_DIAG_F_ALL, "PyLib_startPython: entered: jenv=%p, pyInit=%d, JPy_Module=%p\n", jenv, pyInit, JPy_Module); if (!pyInit) { Py_Initialize(); PyLib_RedirectStdOut(); pyInit = Py_IsInitialized(); } if (pyInit) { if (JPy_DiagFlags != 0) { printf("PyLib_startPython: global Python interpreter information:\n"); #if defined(JPY_COMPAT_33P) printf(" Py_GetProgramName() = \"%ls\"\n", Py_GetProgramName()); printf(" Py_GetPrefix() = \"%ls\"\n", Py_GetPrefix()); printf(" Py_GetExecPrefix() = \"%ls\"\n", Py_GetExecPrefix()); printf(" Py_GetProgramFullPath() = \"%ls\"\n", Py_GetProgramFullPath()); printf(" Py_GetPath() = \"%ls\"\n", Py_GetPath()); printf(" Py_GetPythonHome() = \"%ls\"\n", Py_GetPythonHome()); #elif defined(JPY_COMPAT_27) printf(" Py_GetProgramName() = \"%s\"\n", Py_GetProgramName()); printf(" Py_GetPrefix() = \"%s\"\n", Py_GetPrefix()); printf(" Py_GetExecPrefix() = \"%s\"\n", Py_GetExecPrefix()); printf(" Py_GetProgramFullPath() = \"%s\"\n", Py_GetProgramFullPath()); printf(" Py_GetPath() = \"%s\"\n", Py_GetPath()); printf(" Py_GetPythonHome() = \"%s\"\n", Py_GetPythonHome()); #endif printf(" Py_GetVersion() = \"%s\"\n", Py_GetVersion()); printf(" Py_GetPlatform() = \"%s\"\n", Py_GetPlatform()); printf(" Py_GetCompiler() = \"%s\"\n", Py_GetCompiler()); printf(" Py_GetBuildInfo() = \"%s\"\n", Py_GetBuildInfo()); } // If we've got jPathArray, add all entries to Python's "sys.path" // if (jPathArray != NULL) { PyObject* pyPathList; PyObject* pyPath; jstring jPath; jsize i, pathCount; pathCount = (*jenv)->GetArrayLength(jenv, jPathArray); //printf(">> pathCount=%d\n", pathCount); if (pathCount > 0) { JPy_BEGIN_GIL_STATE pyPathList = PySys_GetObject("path"); //printf(">> pyPathList=%p, len=%ld\n", pyPathList, PyList_Size(pyPathList)); if (pyPathList != NULL) { Py_INCREF(pyPathList); for (i = pathCount - 1; i >= 0; i--) { jPath = (*jenv)->GetObjectArrayElement(jenv, jPathArray, i); //printf(">> i=%d, jPath=%p\n", i, jPath); if (jPath != NULL) { pyPath = JPy_FromJString(jenv, jPath); //printf(">> i=%d, pyPath=%p\n", i, pyPath); if (pyPath != NULL) { PyList_Insert(pyPathList, 0, pyPath); } } } Py_DECREF(pyPathList); } //printf(">> pyPathList=%p, len=%ld\n", pyPathList, PyList_Size(pyPathList)); //printf(">> pyPathList=%p, len=%ld (check)\n", PySys_GetObject("path"), PyList_Size(PySys_GetObject("path"))); JPy_END_GIL_STATE } }
void Py_Initialize(void) { PyInterpreterState *interp; PyThreadState *tstate; PyObject *bimod, *sysmod; char *p; if (initialized) return; initialized = 1; if ((p = getenv("PYTHONDEBUG")) && *p != '\0') Py_DebugFlag = Py_DebugFlag ? Py_DebugFlag : 1; if ((p = getenv("PYTHONVERBOSE")) && *p != '\0') Py_VerboseFlag = Py_VerboseFlag ? Py_VerboseFlag : 1; if ((p = getenv("PYTHONOPTIMIZE")) && *p != '\0') Py_OptimizeFlag = Py_OptimizeFlag ? Py_OptimizeFlag : 1; interp = PyInterpreterState_New(); if (interp == NULL) Py_FatalError("Py_Initialize: can't make first interpreter"); tstate = PyThreadState_New(interp); if (tstate == NULL) Py_FatalError("Py_Initialize: can't make first thread"); (void) PyThreadState_Swap(tstate); interp->modules = PyDict_New(); if (interp->modules == NULL) Py_FatalError("Py_Initialize: can't make modules dictionary"); /* Init codec registry */ _PyCodecRegistry_Init(); /* Init Unicode implementation; relies on the codec registry */ _PyUnicode_Init(); _PyCompareState_Key = PyString_InternFromString("cmp_state"); bimod = _PyBuiltin_Init(); if (bimod == NULL) Py_FatalError("Py_Initialize: can't initialize __builtin__"); interp->builtins = PyModule_GetDict(bimod); Py_INCREF(interp->builtins); sysmod = _PySys_Init(); if (sysmod == NULL) Py_FatalError("Py_Initialize: can't initialize sys"); interp->sysdict = PyModule_GetDict(sysmod); Py_INCREF(interp->sysdict); _PyImport_FixupExtension("sys", "sys"); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); _PyImport_Init(); /* initialize builtin exceptions */ init_exceptions(); /* phase 2 of builtins */ _PyImport_FixupExtension("__builtin__", "__builtin__"); initsigs(); /* Signal handling stuff, including initintr() */ initmain(); /* Module __main__ */ if (!Py_NoSiteFlag) initsite(); /* Module site */ }
void Py_InitializeEx(int install_sigs) { PyInterpreterState *interp; PyThreadState *tstate; PyObject *bimod, *sysmod; char *p; #if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET) char *codeset; char *saved_locale; PyObject *sys_stream, *sys_isatty; #endif extern void _Py_ReadyTypes(void); if (initialized) return; initialized = 1; if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') Py_DebugFlag = add_flag(Py_DebugFlag, p); if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') Py_VerboseFlag = add_flag(Py_VerboseFlag, p); if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); interp = PyInterpreterState_New(); if (interp == NULL) Py_FatalError("Py_Initialize: can't make first interpreter"); tstate = PyThreadState_New(interp); if (tstate == NULL) Py_FatalError("Py_Initialize: can't make first thread"); (void) PyThreadState_Swap(tstate); _Py_ReadyTypes(); if (!_PyFrame_Init()) Py_FatalError("Py_Initialize: can't init frames"); if (!_PyInt_Init()) Py_FatalError("Py_Initialize: can't init ints"); _PyFloat_Init(); interp->modules = PyDict_New(); if (interp->modules == NULL) Py_FatalError("Py_Initialize: can't make modules dictionary"); interp->modules_reloading = PyDict_New(); if (interp->modules_reloading == NULL) Py_FatalError("Py_Initialize: can't make modules_reloading dictionary"); #ifdef Py_USING_UNICODE /* Init Unicode implementation; relies on the codec registry */ _PyUnicode_Init(); #endif bimod = _PyBuiltin_Init(); if (bimod == NULL) Py_FatalError("Py_Initialize: can't initialize __builtin__"); interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) Py_FatalError("Py_Initialize: can't initialize builtins dict"); Py_INCREF(interp->builtins); sysmod = _PySys_Init(); if (sysmod == NULL) Py_FatalError("Py_Initialize: can't initialize sys"); interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) Py_FatalError("Py_Initialize: can't initialize sys dict"); Py_INCREF(interp->sysdict); _PyImport_FixupExtension("sys", "sys"); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); _PyImport_Init(); /* initialize builtin exceptions */ _PyExc_Init(); _PyImport_FixupExtension("exceptions", "exceptions"); /* phase 2 of builtins */ _PyImport_FixupExtension("__builtin__", "__builtin__"); _PyImportHooks_Init(); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ initmain(); /* Module __main__ */ if (!Py_NoSiteFlag) initsite(); /* Module site */ /* auto-thread-state API, if available */ #ifdef WITH_THREAD _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ warnings_module = PyImport_ImportModule("warnings"); if (!warnings_module) PyErr_Clear(); #if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET) /* On Unix, set the file system encoding according to the user's preference, if the CODESET names a well-known Python codec, and Py_FileSystemDefaultEncoding isn't initialized by other means. Also set the encoding of stdin and stdout if these are terminals. */ saved_locale = strdup(setlocale(LC_CTYPE, NULL)); setlocale(LC_CTYPE, ""); codeset = nl_langinfo(CODESET); if (codeset && *codeset) { PyObject *enc = PyCodec_Encoder(codeset); if (enc) { codeset = strdup(codeset); Py_DECREF(enc); } else { codeset = NULL; PyErr_Clear(); } } else codeset = NULL; setlocale(LC_CTYPE, saved_locale); free(saved_locale); if (codeset) { sys_stream = PySys_GetObject("stdin"); sys_isatty = PyObject_CallMethod(sys_stream, "isatty", ""); if (!sys_isatty) PyErr_Clear(); if(sys_isatty && PyObject_IsTrue(sys_isatty) && PyFile_Check(sys_stream)) { if (!PyFile_SetEncoding(sys_stream, codeset)) Py_FatalError("Cannot set codeset of stdin"); } Py_XDECREF(sys_isatty); sys_stream = PySys_GetObject("stdout"); sys_isatty = PyObject_CallMethod(sys_stream, "isatty", ""); if (!sys_isatty) PyErr_Clear(); if(sys_isatty && PyObject_IsTrue(sys_isatty) && PyFile_Check(sys_stream)) { if (!PyFile_SetEncoding(sys_stream, codeset)) Py_FatalError("Cannot set codeset of stdout"); } Py_XDECREF(sys_isatty); sys_stream = PySys_GetObject("stderr"); sys_isatty = PyObject_CallMethod(sys_stream, "isatty", ""); if (!sys_isatty) PyErr_Clear(); if(sys_isatty && PyObject_IsTrue(sys_isatty) && PyFile_Check(sys_stream)) { if (!PyFile_SetEncoding(sys_stream, codeset)) Py_FatalError("Cannot set codeset of stderr"); } Py_XDECREF(sys_isatty); if (!Py_FileSystemDefaultEncoding) Py_FileSystemDefaultEncoding = codeset; else free(codeset); } #endif }
void XBPyThread::Process() { CLog::Log(LOGDEBUG,"Python thread: start processing"); char path[1024]; char sourcedir[1024]; // get the global lock PyEval_AcquireLock(); m_threadState = Py_NewInterpreter(); PyEval_ReleaseLock(); if (!m_threadState) { CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!"); return; } PyEval_AcquireLock(); // swap in my thread state PyThreadState_Swap(m_threadState); m_pExecuter->InitializeInterpreter(); // get path from script file name and add python path's // this is used for python so it will search modules from script path first strcpy(sourcedir, source); #ifndef _LINUX strcpy(strrchr(sourcedir, PATH_SEPARATOR_CHAR), ";"); #else strcpy(strrchr(sourcedir, PATH_SEPARATOR_CHAR), ":"); #endif strcpy(path, sourcedir); #ifndef _LINUX strcat(path, dll_getenv("PYTHONPATH")); #else #ifdef __APPLE__ strcat(path, _P("Q:\\system\\python\\python24.zlib:")); strcat(path, _P("Q:\\system\\python\\lib-osx")); #else strcat(path, Py_GetPath()); #endif #endif // set current directory and python's path. if (argv != NULL) { PySys_SetArgv(argc, argv); } PySys_SetPath(path); #ifdef _LINUX // Replace the : at the end with ; so it will be EXACTLY like the xbox version strcpy(strrchr(sourcedir, ':'), ";"); #endif xbp_chdir(sourcedir); // XXX, there is a ';' at the end if (type == 'F') { // run script from file FILE *fp = fopen(source, "r"); if (fp) { if (PyRun_SimpleFile(fp, source) == -1) { CLog::Log(LOGERROR, "Scriptresult: Error\n"); if (PyErr_Occurred()) PyErr_Print(); } else CLog::Log(LOGINFO, "Scriptresult: Succes\n"); fclose(fp); } else CLog::Log(LOGERROR, "%s not found!\n", source); } else { //run script if (PyRun_SimpleString(source) == -1) { CLog::Log(LOGERROR, "Scriptresult: Error\n"); if (PyErr_Occurred()) PyErr_Print(); } else CLog::Log(LOGINFO, "Scriptresult: Success\n"); } PyEval_ReleaseLock(); // when a script uses threads or timers - we have to wait for them to be over before we terminate the interpreter. // so first - release the lock and allow the threads to terminate. ::Sleep(500); PyEval_AcquireLock(); PyThreadState_Swap(m_threadState); // look waiting for the running threads to end PyRun_SimpleString( "import threading\n" "import sys\n" "try:\n" "\tthreads = list(threading.enumerate())\n" "except:\n" "\tprint 'error listing threads'\n" "while threading.activeCount() > 1:\n" "\tfor thread in threads:\n" "\t\tif thread <> threading.currentThread():\n" "\t\t\tprint 'waiting for thread - ' + thread.getName()\n" "\t\t\tthread.join(1000)\n" ); m_pExecuter->DeInitializeInterpreter(); Py_EndInterpreter(m_threadState); m_threadState = NULL; PyEval_ReleaseLock(); }
PyThreadState * Py_NewInterpreter(void) { PyInterpreterState *interp; PyThreadState *tstate, *save_tstate; PyObject *bimod, *sysmod; if (!initialized) Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); #ifdef WITH_THREAD /* Issue #10915, #15751: The GIL API doesn't work with multiple interpreters: disable PyGILState_Check(). */ _PyGILState_check_enabled = 0; #endif interp = PyInterpreterState_New(); if (interp == NULL) return NULL; tstate = PyThreadState_New(interp); if (tstate == NULL) { PyInterpreterState_Delete(interp); return NULL; } save_tstate = PyThreadState_Swap(tstate); /* XXX The following is lax in error checking */ interp->modules = PyDict_New(); bimod = _PyImport_FindBuiltin("builtins"); if (bimod != NULL) { interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) goto handle_error; Py_INCREF(interp->builtins); } /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PyImport_FindBuiltin("sys"); if (bimod != NULL && sysmod != NULL) { PyObject *pstderr; interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) goto handle_error; Py_INCREF(interp->sysdict); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImportHooks_Init(); import_init(interp, sysmod); if (initfsencoding(interp) < 0) goto handle_error; if (initstdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); initmain(interp); if (!Py_NoSiteFlag) initsite(); } if (!PyErr_Occurred()) return tstate; handle_error: /* Oops, it didn't work. Undo it all. */ PyErr_PrintEx(0); PyThreadState_Clear(tstate); PyThreadState_Swap(save_tstate); PyThreadState_Delete(tstate); PyInterpreterState_Delete(interp); return NULL; }
static void addPyPath() { std::string path = getResourcePath() + "/Python:" + Py_GetPath(); PySys_SetPath((char*)path.c_str()); if(!forkExecProc) printf("Python path: %s\n", path.c_str()); }
void XBPyThread::Process() { CLog::Log(LOGDEBUG,"Python thread: start processing"); int m_Py_file_input = Py_file_input; // get the global lock PyEval_AcquireLock(); PyThreadState* state = Py_NewInterpreter(); if (!state) { PyEval_ReleaseLock(); CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!"); return; } // swap in my thread state PyThreadState_Swap(state); XBMCAddon::AddonClass::Ref<XBMCAddon::Python::LanguageHook> languageHook(new XBMCAddon::Python::LanguageHook(state->interp)); languageHook->RegisterMe(); m_pExecuter->InitializeInterpreter(addon); CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source); // get path from script file name and add python path's // this is used for python so it will search modules from script path first CStdString scriptDir; URIUtils::GetDirectory(CSpecialProtocol::TranslatePath(m_source), scriptDir); URIUtils::RemoveSlashAtEnd(scriptDir); CStdString path = scriptDir; // add on any addon modules the user has installed ADDON::VECADDONS addons; ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons); for (unsigned int i = 0; i < addons.size(); ++i) #ifdef TARGET_WINDOWS { CStdString strTmp(CSpecialProtocol::TranslatePath(addons[i]->LibPath())); g_charsetConverter.utf8ToSystem(strTmp); path += PY_PATH_SEP + strTmp; } #else path += PY_PATH_SEP + CSpecialProtocol::TranslatePath(addons[i]->LibPath()); #endif // and add on whatever our default path is path += PY_PATH_SEP; // we want to use sys.path so it includes site-packages // if this fails, default to using Py_GetPath PyObject *sysMod(PyImport_ImportModule((char*)"sys")); // must call Py_DECREF when finished PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete if( pathObj && PyList_Check(pathObj) ) { for( int i = 0; i < PyList_Size(pathObj); i++ ) { PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete if( e && PyString_Check(e) ) { path += PyString_AsString(e); // returns internal data, don't delete or modify path += PY_PATH_SEP; } } } else { path += Py_GetPath(); } Py_DECREF(sysMod); // release ref to sysMod // set current directory and python's path. if (m_argv != NULL) PySys_SetArgv(m_argc, m_argv); CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str()); PySys_SetPath((char *)path.c_str()); CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str()); PyObject* module = PyImport_AddModule((char*)"__main__"); PyObject* moduleDict = PyModule_GetDict(module); // when we are done initing we store thread state so we can be aborted PyThreadState_Swap(NULL); PyEval_ReleaseLock(); // we need to check if we was asked to abort before we had inited bool stopping = false; { CSingleLock lock(m_pExecuter->m_critSection); m_threadState = state; stopping = m_stopping; } PyEval_AcquireLock(); PyThreadState_Swap(state); if (!stopping) { try { if (m_type == 'F') { // run script from file // We need to have python open the file because on Windows the DLL that python // is linked against may not be the DLL that xbmc is linked against so // passing a FILE* to python from an fopen has the potential to crash. PyObject* file = PyFile_FromString((char *) CSpecialProtocol::TranslatePath(m_source).c_str(), (char*)"r"); FILE *fp = PyFile_AsFile(file); if (fp) { PyObject *f = PyString_FromString(CSpecialProtocol::TranslatePath(m_source).c_str()); PyDict_SetItemString(moduleDict, "__file__", f); if (addon.get() != NULL) { PyObject *pyaddonid = PyString_FromString(addon->ID().c_str()); PyDict_SetItemString(moduleDict, "__xbmcaddonid__", pyaddonid); CStdString version = ADDON::GetXbmcApiVersionDependency(addon); PyObject *pyxbmcapiversion = PyString_FromString(version.c_str()); PyDict_SetItemString(moduleDict, "__xbmcapiversion__", pyxbmcapiversion); CLog::Log(LOGDEBUG,"Instantiating addon using automatically obtained id of \"%s\" dependent on version %s of the xbmc.python api",addon->ID().c_str(),version.c_str()); } Py_DECREF(f); XBMCAddon::Python::PyContext pycontext; // this is a guard class that marks this callstack as being in a python context PyRun_FileExFlags(fp, CSpecialProtocol::TranslatePath(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict,1,NULL); } else CLog::Log(LOGERROR, "%s not found!", m_source); } else { //run script PyRun_String(m_source, m_Py_file_input, moduleDict, moduleDict); } } catch (const XbmcCommons::Exception& e) { e.LogThrowMessage(); } catch (...) { CLog::Log(LOGERROR, "failure in %s", m_source); } } if (!PyErr_Occurred()) CLog::Log(LOGINFO, "Scriptresult: Success"); else if (PyErr_ExceptionMatches(PyExc_SystemExit)) CLog::Log(LOGINFO, "Scriptresult: Aborted"); else { PythonBindings::PythonToCppException e; e.LogThrowMessage(); { CPyThreadState releaseGil; CSingleLock gc(g_graphicsContext); CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST); if (pDlgToast) { CStdString desc; CStdString path; CStdString script; URIUtils::Split(m_source, path, script); if (script.Equals("default.py")) { CStdString path2; URIUtils::RemoveSlashAtEnd(path); URIUtils::Split(path, path2, script); } desc.Format(g_localizeStrings.Get(2100), script); pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc); } } } PyObject *m = PyImport_AddModule((char*)"xbmc"); if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1))) CLog::Log(LOGERROR, "Scriptresult: failed to set abortRequested"); // make sure all sub threads have finished for(PyThreadState* s = state->interp->tstate_head, *old = NULL; s;) { if(s == state) { s = s->next; continue; } if(old != s) { CLog::Log(LOGINFO, "Scriptresult: Waiting on thread %"PRIu64, (uint64_t)s->thread_id); old = s; } CPyThreadState pyState; Sleep(100); pyState.Restore(); s = state->interp->tstate_head; } // pending calls must be cleared out XBMCAddon::RetardedAsynchCallbackHandler::clearPendingCalls(state); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); //set stopped event - this allows ::stop to run and kill remaining threads //this event has to be fired without holding m_pExecuter->m_critSection //before //Also the GIL (PyEval_AcquireLock) must not be held //if not obeyed there is still no deadlock because ::stop waits with timeout (smart one!) stoppedEvent.Set(); { CSingleLock lock(m_pExecuter->m_critSection); m_threadState = NULL; } PyEval_AcquireLock(); PyThreadState_Swap(state); m_pExecuter->DeInitializeInterpreter(); // run the gc before finishing if (!m_stopping && languageHook->HasRegisteredAddonClasses() && PyRun_SimpleString(GC_SCRIPT) == -1) CLog::Log(LOGERROR,"Failed to run the gc to clean up after running prior to shutting down the Interpreter %s",m_source); Py_EndInterpreter(state); // This is a total hack. Python doesn't necessarily release // all of the objects associated with the interpreter when // you end the interpreter. As a result there are objects // managed by the windowing system that still receive events // until python decides to clean them up. Python will eventually // clean them up on the creation or ending of a subsequent // interpreter. So we are going to keep creating and ending // interpreters until we have no more python objects hanging // around. if (languageHook->HasRegisteredAddonClasses()) { CLog::Log(LOGDEBUG, "The python script \"%s\" has left several " "classes in memory that we will be attempting to clean up. The classes include: %s", m_source, getListOfAddonClassesAsString(languageHook).c_str()); int countLimit; for (countLimit = 0; languageHook->HasRegisteredAddonClasses() && countLimit < 100; countLimit++) { PyThreadState* tmpstate = Py_NewInterpreter(); PyThreadState* oldstate = PyThreadState_Swap(tmpstate); if (PyRun_SimpleString(GC_SCRIPT) == -1) CLog::Log(LOGERROR,"Failed to run the gc to clean up after running %s",m_source); PyThreadState_Swap(oldstate); Py_EndInterpreter(tmpstate); } // If necessary and successfull, debug log the results. if (countLimit > 0 && !languageHook->HasRegisteredAddonClasses()) CLog::Log(LOGDEBUG,"It took %d Py_NewInterpreter/Py_EndInterpreter calls" " to clean up the classes leftover from running \"%s.\"", countLimit,m_source); // If not successful, produce an error message detailing what's been left behind if (languageHook->HasRegisteredAddonClasses()) CLog::Log(LOGERROR, "The python script \"%s\" has left several " "classes in memory that we couldn't clean up. The classes include: %s", m_source, getListOfAddonClassesAsString(languageHook).c_str()); } // unregister the language hook languageHook->UnregisterMe(); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); }
void _Py_InitializeEx_Private(int install_sigs, int install_importlib) { PyInterpreterState *interp; PyThreadState *tstate; PyObject *bimod, *sysmod, *pstderr; char *p; extern void _Py_ReadyTypes(void); if (initialized) return; initialized = 1; _Py_Finalizing = NULL; #if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE) /* Set up the LC_CTYPE locale, so we can obtain the locale's charset without having to switch locales. */ setlocale(LC_CTYPE, ""); #endif if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') Py_DebugFlag = add_flag(Py_DebugFlag, p); if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') Py_VerboseFlag = add_flag(Py_VerboseFlag, p); if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); /* The variable is only tested for existence here; _PyRandom_Init will check its value further. */ if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0') Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p); _PyRandom_Init(); interp = PyInterpreterState_New(); if (interp == NULL) Py_FatalError("Py_Initialize: can't make first interpreter"); tstate = PyThreadState_New(interp); if (tstate == NULL) Py_FatalError("Py_Initialize: can't make first thread"); (void) PyThreadState_Swap(tstate); #ifdef WITH_THREAD /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because destroying the GIL might fail when it is being referenced from another running thread (see issue #9901). Instead we destroy the previously created GIL here, which ensures that we can call Py_Initialize / Py_FinalizeEx multiple times. */ _PyEval_FiniThreads(); /* Auto-thread-state API */ _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ _Py_ReadyTypes(); if (!_PyFrame_Init()) Py_FatalError("Py_Initialize: can't init frames"); if (!_PyLong_Init()) Py_FatalError("Py_Initialize: can't init longs"); if (!PyByteArray_Init()) Py_FatalError("Py_Initialize: can't init bytearray"); if (!_PyFloat_Init()) Py_FatalError("Py_Initialize: can't init float"); interp->modules = PyDict_New(); if (interp->modules == NULL) Py_FatalError("Py_Initialize: can't make modules dictionary"); /* Init Unicode implementation; relies on the codec registry */ if (_PyUnicode_Init() < 0) Py_FatalError("Py_Initialize: can't initialize unicode"); if (_PyStructSequence_Init() < 0) Py_FatalError("Py_Initialize: can't initialize structseq"); bimod = _PyBuiltin_Init(); if (bimod == NULL) Py_FatalError("Py_Initialize: can't initialize builtins modules"); _PyImport_FixupBuiltin(bimod, "builtins"); interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) Py_FatalError("Py_Initialize: can't initialize builtins dict"); Py_INCREF(interp->builtins); /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PySys_Init(); if (sysmod == NULL) Py_FatalError("Py_Initialize: can't initialize sys"); interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) Py_FatalError("Py_Initialize: can't initialize sys dict"); Py_INCREF(interp->sysdict); _PyImport_FixupBuiltin(sysmod, "sys"); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImport_Init(); _PyImportHooks_Init(); /* Initialize _warnings. */ _PyWarnings_Init(); if (!install_importlib) return; if (_PyTime_Init() < 0) Py_FatalError("Py_Initialize: can't initialize time"); import_init(interp, sysmod); /* initialize the faulthandler module */ if (_PyFaulthandler_Init()) Py_FatalError("Py_Initialize: can't initialize faulthandler"); if (initfsencoding(interp) < 0) Py_FatalError("Py_Initialize: unable to load the file system codec"); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ if (_PyTraceMalloc_Init() < 0) Py_FatalError("Py_Initialize: can't initialize tracemalloc"); initmain(interp); /* Module __main__ */ if (initstdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); /* Initialize warnings. */ if (PySys_HasWarnOptions()) { PyObject *warnings_module = PyImport_ImportModule("warnings"); if (warnings_module == NULL) { fprintf(stderr, "'import warnings' failed; traceback:\n"); PyErr_Print(); } Py_XDECREF(warnings_module); } if (!Py_NoSiteFlag) initsite(); /* Module site */ }
std::wstring PySetup::get_path() { return Py_GetPath(); }
int main( int argc, char ** argv ) { #if defined (FC_OS_LINUX) || defined(FC_OS_BSD) // Make sure to setup the Qt locale system before setting LANG and LC_ALL to C. // which is needed to use the system locale settings. (void)QLocale::system(); #if QT_VERSION < 0x050000 // http://www.freecadweb.org/tracker/view.php?id=399 // Because of setting LANG=C the Qt automagic to use the correct encoding // for file names is broken. This is a workaround to force the use of UTF-8 encoding QFile::setEncodingFunction(myEncoderFunc); QFile::setDecodingFunction(myDecoderFunc); #endif // See https://forum.freecadweb.org/viewtopic.php?f=18&t=20600 // See Gui::Application::runApplication() putenv("LC_NUMERIC=C"); putenv("PYTHONPATH="); #elif defined(FC_OS_MACOSX) (void)QLocale::system(); putenv("PYTHONPATH="); #else _putenv("PYTHONPATH="); // https://forum.freecadweb.org/viewtopic.php?f=4&t=18288 // https://forum.freecadweb.org/viewtopic.php?f=3&t=20515 const char* fc_py_home = getenv("FC_PYTHONHOME"); if (fc_py_home) _putenv_s("PYTHONHOME", fc_py_home); else _putenv("PYTHONHOME="); #endif #if defined (FC_OS_WIN32) int argc_ = argc; QVector<QByteArray> data; QVector<char *> argv_; // get the command line arguments as unicode string { QCoreApplication app(argc, argv); QStringList args = app.arguments(); for (QStringList::iterator it = args.begin(); it != args.end(); ++it) { data.push_back(it->toUtf8()); argv_.push_back(data.back().data()); } argv_.push_back(0); // 0-terminated string } #endif #if PY_MAJOR_VERSION >= 3 #if defined(_MSC_VER) && _MSC_VER <= 1800 // See InterpreterSingleton::init Redirection out(stdout), err(stderr), inp(stdin); #endif #endif // PY_MAJOR_VERSION // Name and Version of the Application App::Application::Config()["ExeName"] = "FreeCAD"; App::Application::Config()["ExeVendor"] = "FreeCAD"; App::Application::Config()["AppDataSkipVendor"] = "true"; App::Application::Config()["MaintainerUrl"] = "http://www.freecadweb.org/wiki/Main_Page"; // set the banner (for logging and console) App::Application::Config()["CopyrightInfo"] = sBanner; App::Application::Config()["AppIcon"] = "freecad"; App::Application::Config()["SplashScreen"] = "freecadsplash"; App::Application::Config()["StartWorkbench"] = "StartWorkbench"; //App::Application::Config()["HiddenDockWindow"] = "Property editor"; App::Application::Config()["SplashAlignment" ] = "Bottom|Left"; App::Application::Config()["SplashTextColor" ] = "#ffffff"; // white App::Application::Config()["SplashInfoColor" ] = "#c8c8c8"; // light grey try { // Init phase =========================================================== // sets the default run mode for FC, starts with gui if not overridden in InitConfig... App::Application::Config()["RunMode"] = "Gui"; App::Application::Config()["Console"] = "0"; // Inits the Application #if defined (FC_OS_WIN32) App::Application::init(argc_, argv_.data()); #else App::Application::init(argc, argv); #endif #if defined(_MSC_VER) // create a dump file when the application crashes std::string dmpfile = App::Application::getUserAppDataDir(); dmpfile += "crash.dmp"; InitMiniDumpWriter(dmpfile); #endif std::map<std::string, std::string>::iterator it = App::Application::Config().find("NavigationStyle"); if (it != App::Application::Config().end()) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); // if not already defined do it now (for the very first start) std::string style = hGrp->GetASCII("NavigationStyle", it->second.c_str()); hGrp->SetASCII("NavigationStyle", style.c_str()); } Gui::Application::initApplication(); // Only if 'RunMode' is set to 'Gui' do the replacement if (App::Application::Config()["RunMode"] == "Gui") Base::Interpreter().replaceStdOutput(); } catch (const Base::UnknownProgramOption& e) { QApplication app(argc,argv); QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str()); QString msg = QString::fromLatin1(e.what()); QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>"); QMessageBox::critical(0, appName, s); exit(1); } catch (const Base::ProgramInformation& e) { QApplication app(argc,argv); QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str()); QString msg = QString::fromUtf8(e.what()); QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>"); QMessageBox msgBox; msgBox.setIcon(QMessageBox::Information); msgBox.setWindowTitle(appName); msgBox.setDetailedText(msg); msgBox.setText(s); msgBox.exec(); exit(0); } catch (const Base::Exception& e) { // Popup an own dialog box instead of that one of Windows QApplication app(argc,argv); QString appName = QString::fromLatin1(App::Application::Config()["ExeName"].c_str()); QString msg; msg = QObject::tr("While initializing %1 the following exception occurred: '%2'\n\n" "Python is searching for its files in the following directories:\n%3\n\n" "Python version information:\n%4\n") .arg(appName).arg(QString::fromUtf8(e.what())) #if PY_MAJOR_VERSION >= 3 #if PY_MINOR_VERSION >= 5 .arg(QString::fromUtf8(Py_EncodeLocale(Py_GetPath(),NULL))).arg(QString::fromLatin1(Py_GetVersion())); #else .arg(QString::fromUtf8(_Py_wchar2char(Py_GetPath(),NULL))).arg(QString::fromLatin1(Py_GetVersion())); #endif #else .arg(QString::fromUtf8(Py_GetPath())).arg(QString::fromLatin1(Py_GetVersion()));
void XBPyThread::Process() { CLog::Log(LOGDEBUG,"Python thread: start processing"); int m_Py_file_input = Py_file_input; // get the global lock PyEval_AcquireLock(); PyThreadState* state = Py_NewInterpreter(); if (!state) { PyEval_ReleaseLock(); CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!"); return; } // swap in my thread state PyThreadState_Swap(state); m_pExecuter->InitializeInterpreter(); CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source); // get path from script file name and add python path's // this is used for python so it will search modules from script path first CStdString scriptDir; URIUtils::GetDirectory(_P(m_source), scriptDir); URIUtils::RemoveSlashAtEnd(scriptDir); CStdString path = scriptDir; // add on any addon modules the user has installed ADDON::VECADDONS addons; ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons); for (unsigned int i = 0; i < addons.size(); ++i) path += PY_PATH_SEP + _P(addons[i]->LibPath()); // and add on whatever our default path is path += PY_PATH_SEP; { // we want to use sys.path so it includes site-packages // if this fails, default to using Py_GetPath PyObject *sysMod(PyImport_ImportModule((char*)"sys")); // must call Py_DECREF when finished PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete if( pathObj && PyList_Check(pathObj) ) { for( int i = 0; i < PyList_Size(pathObj); i++ ) { PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete if( e && PyString_Check(e) ) { path += PyString_AsString(e); // returns internal data, don't delete or modify path += PY_PATH_SEP; } } } else { path += Py_GetPath(); } Py_DECREF(sysMod); // release ref to sysMod } // set current directory and python's path. if (m_argv != NULL) PySys_SetArgv(m_argc, m_argv); CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str()); PySys_SetPath((char *)path.c_str()); CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str()); PyObject* module = PyImport_AddModule((char*)"__main__"); PyObject* moduleDict = PyModule_GetDict(module); // when we are done initing we store thread state so we can be aborted PyThreadState_Swap(NULL); PyEval_ReleaseLock(); // we need to check if we was asked to abort before we had inited bool stopping = false; { CSingleLock lock(m_pExecuter->m_critSection); m_threadState = state; stopping = m_stopping; } PyEval_AcquireLock(); PyThreadState_Swap(state); if (!stopping) { if (m_type == 'F') { // run script from file // We need to have python open the file because on Windows the DLL that python // is linked against may not be the DLL that xbmc is linked against so // passing a FILE* to python from an fopen has the potential to crash. PyObject* file = PyFile_FromString((char *) _P(m_source).c_str(), (char*)"r"); FILE *fp = PyFile_AsFile(file); if (fp) { PyObject *f = PyString_FromString(_P(m_source).c_str()); PyDict_SetItemString(moduleDict, "__file__", f); Py_DECREF(f); PyRun_File(fp, _P(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict); // Get a reference to the main module // and global dictionary PyObject* main_module = PyImport_AddModule((char*)"__main__"); PyObject* global_dict = PyModule_GetDict(main_module); // Extract a reference to the function "func_name" // from the global dictionary PyObject* expression = PyDict_GetItemString(global_dict, "xbmcclosefilehack"); if (!PyObject_CallFunction(expression,(char*)"(O)",file)) CLog::Log(LOGERROR,"Failed to close the script file %s",_P(m_source).c_str()); } else CLog::Log(LOGERROR, "%s not found!", m_source); } else { //run script PyRun_String(m_source, m_Py_file_input, moduleDict, moduleDict); } } if (!PyErr_Occurred()) CLog::Log(LOGINFO, "Scriptresult: Success"); else if (PyErr_ExceptionMatches(PyExc_SystemExit)) CLog::Log(LOGINFO, "Scriptresult: Aborted"); else { PyObject* exc_type; PyObject* exc_value; PyObject* exc_traceback; PyObject* pystring; pystring = NULL; PyErr_Fetch(&exc_type, &exc_value, &exc_traceback); if (exc_type == 0 && exc_value == 0 && exc_traceback == 0) { CLog::Log(LOGINFO, "Strange: No Python exception occured"); } else { if (exc_type != NULL && (pystring = PyObject_Str(exc_type)) != NULL && (PyString_Check(pystring))) { PyObject *tracebackModule; CLog::Log(LOGINFO, "-->Python script returned the following error<--"); CLog::Log(LOGERROR, "Error Type: %s", PyString_AsString(PyObject_Str(exc_type))); if (PyObject_Str(exc_value)) CLog::Log(LOGERROR, "Error Contents: %s", PyString_AsString(PyObject_Str(exc_value))); tracebackModule = PyImport_ImportModule((char*)"traceback"); if (tracebackModule != NULL) { PyObject *tbList, *emptyString, *strRetval; tbList = PyObject_CallMethod(tracebackModule, (char*)"format_exception", (char*)"OOO", exc_type, exc_value == NULL ? Py_None : exc_value, exc_traceback == NULL ? Py_None : exc_traceback); emptyString = PyString_FromString(""); strRetval = PyObject_CallMethod(emptyString, (char*)"join", (char*)"O", tbList); CLog::Log(LOGERROR, "%s", PyString_AsString(strRetval)); Py_DECREF(tbList); Py_DECREF(emptyString); Py_DECREF(strRetval); Py_DECREF(tracebackModule); } CLog::Log(LOGINFO, "-->End of Python script error report<--"); } else { pystring = NULL; CLog::Log(LOGINFO, "<unknown exception type>"); } CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST); if (pDlgToast) { CStdString desc; CStdString path; CStdString script; URIUtils::Split(m_source, path, script); if (script.Equals("default.py")) { CStdString path2; URIUtils::RemoveSlashAtEnd(path); URIUtils::Split(path, path2, script); } desc.Format(g_localizeStrings.Get(2100), script); pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc); } } Py_XDECREF(exc_type); Py_XDECREF(exc_value); // caller owns all 3 Py_XDECREF(exc_traceback); // already NULL'd out Py_XDECREF(pystring); } PyObject *m = PyImport_AddModule((char*)"xbmc"); if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1))) CLog::Log(LOGERROR, "Scriptresult: failed to set abortRequested"); // make sure all sub threads have finished for(PyThreadState* s = state->interp->tstate_head, *old = NULL; s;) { if(s == state) { s = s->next; continue; } if(old != s) { CLog::Log(LOGINFO, "Scriptresult: Waiting on thread %"PRIu64, (uint64_t)s->thread_id); old = s; } CPyThreadState pyState; Sleep(100); pyState.Restore(); s = state->interp->tstate_head; } // pending calls must be cleared out PyXBMC_ClearPendingCalls(state); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); { CSingleLock lock(m_pExecuter->m_critSection); m_threadState = NULL; } PyEval_AcquireLock(); PyThreadState_Swap(state); m_pExecuter->DeInitializeInterpreter(); Py_EndInterpreter(state); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); }
mitk::PythonService::PythonService() : m_ItkWrappingAvailable( true ), m_OpenCVWrappingAvailable( true ), m_VtkWrappingAvailable( true ), m_ErrorOccured( false ) { { MITK_DEBUG << "will init python if necessary"; } bool pythonInitialized = static_cast<bool>( Py_IsInitialized() ); //m_PythonManager.isPythonInitialized() ); { MITK_DEBUG << "pythonInitialized " << pythonInitialized; MITK_DEBUG << "m_PythonManager.isPythonInitialized() " << m_PythonManager.isPythonInitialized(); } // due to strange static var behaviour on windows Py_IsInitialized() returns correct value while // m_PythonManager.isPythonInitialized() does not because it has been constructed and destructed again if( !m_PythonManager.isPythonInitialized() ) { try { //TODO a better way to do this #ifndef WIN32 #if defined (__APPLE__) || defined(MACOSX) const char* library = "libpython${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}.dylib"; #else const char* library = "libpython${PYTHON_VERSION_MAJOR}.${PYTHON_VERSION_MINOR}.so"; #endif dlerror(); if(dlopen(library, RTLD_NOW | RTLD_GLOBAL) == 0 ) { mitkThrow() << "Python runtime could not be loaded: " << dlerror(); } #endif std::string programPath = mitk::IOUtil::GetProgramPath(); QDir programmDir( QString( programPath.c_str() ).append("/Python") ); QString pythonCommand; // TODO: Check this in the modernization branch with an installer // Set the pythonpath variable depending if // we have an installer or development environment if ( programmDir.exists() ) { // runtime directory used in installers pythonCommand.append( QString("import site, sys\n") ); pythonCommand.append( QString("sys.path.append('')\n") ); pythonCommand.append( QString("sys.path.append('%1')\n").arg(programPath.c_str()) ); pythonCommand.append( QString("sys.path.append('%1/Python')").arg(programPath.c_str()) ); // development } else { pythonCommand.append( QString("import site, sys\n") ); pythonCommand.append( QString("sys.path.append('')\n") ); pythonCommand.append( QString("sys.path.append('%1')\n").arg(EXTERNAL_DIST_PACKAGES) ); pythonCommand.append( QString("\nsite.addsitedir('%1')").arg(EXTERNAL_SITE_PACKAGES) ); } if( pythonInitialized ) m_PythonManager.setInitializationFlags(PythonQt::RedirectStdOut|PythonQt::PythonAlreadyInitialized); else m_PythonManager.setInitializationFlags(PythonQt::RedirectStdOut); // set python home if own runtime is used #ifdef USE_MITK_BUILTIN_PYTHON QString pythonHome; if ( programmDir.exists() ) pythonHome.append(QString("%1/Python").arg(programPath.c_str())); else pythonHome.append(PYTHONHOME); if(pHome) delete[] pHome; pHome = new char[pythonHome.toStdString().length() + 1]; strcpy(pHome,pythonHome.toStdString().c_str()); Py_SetPythonHome(pHome); MITK_DEBUG("PythonService") << "PythonHome: " << pHome; #endif MITK_DEBUG("PythonService") << "initalizing python"; m_PythonManager.initialize(); #ifdef USE_MITK_BUILTIN_PYTHON PyObject* dict = PyDict_New(); // Import builtin modules if (PyDict_GetItemString(dict, "__builtins__") == nullptr) { PyObject* builtinMod = PyImport_ImportModule("__builtin__"); if (builtinMod == nullptr || PyDict_SetItemString(dict, "__builtins__", builtinMod) != 0) { Py_DECREF(dict); Py_XDECREF(dict); return; } Py_DECREF(builtinMod); } #endif MITK_DEBUG("PythonService")<< "Python Search paths: " << Py_GetPath(); MITK_DEBUG("PythonService") << "python initalized"; //MITK_DEBUG("PythonService") << "registering python paths" << PYTHONPATH_COMMAND; m_PythonManager.executeString( pythonCommand, ctkAbstractPythonManager::FileInput ); } catch (...) { MITK_DEBUG("PythonService") << "exception initalizing python"; } } }
void Settings::load() { const char* settingsFile = "CONFIG:config.py"; try{ main = python::import("__main__"); python::object global = main.attr("__dict__"); local = python::dict(); if (ResMan::Instance()->exists(settingsFile)) { //TODO: Handle missing values python::object result = python::exec_file(ResMan::Instance()->getRealPath(settingsFile).c_str(), global, local); m_dataDir = python::extract<std::string>(local["config"]["data_dir"]); m_debug = python::extract<int>(local["config"]["debug"]); m_gameSpeed = python::extract<int>(local["config"]["game_speed"]); m_gameDir = python::extract<std::string>(local["config"]["game_dir"]); m_playIntro = python::extract<bool>(local["config"]["play_intro"]); m_resolution.x = python::extract<int>(local["config"]["graphics"]["width"]); m_resolution.y = python::extract<int>(local["config"]["graphics"]["height"]); m_fullscreen = python::extract<bool>(local["config"]["graphics"]["fullscreen"]); m_doubleBuffered = python::extract<bool>(local["config"]["graphics"]["double_buffered"]); m_soundOn = python::extract<bool>(local["config"]["sound"]["sound_on"]); m_sfxVolume = python::extract<int>(local["config"]["sound"]["sound_volume"]); m_responseVolume = python::extract<int>(local["config"]["sound"]["response_volume"]); m_voiceVolume = python::extract<int>(local["config"]["sound"]["voice_volume"]); m_musicOn = python::extract<bool>(local["config"]["sound"]["music_on"]); m_musicVolume = python::extract<int>(local["config"]["sound"]["music_volume"]); m_emuOpl = python::extract<int>(local["config"]["sound"]["opl_emulator"]); } else { python::exec("config = {'graphics' : dict(), 'sound' : dict()}", global, local); local["config"]["data_dir"] = m_dataDir = "DUNE2"; local["config"]["debug"] = m_debug = 8; local["config"]["game_speed"] = m_gameSpeed = 4; local["config"]["game_dir"] = m_gameDir = GAME_DIR; local["config"]["play_intro"] = m_playIntro = false; local["config"]["graphics"]["width"] = m_resolution.x = 640; local["config"]["graphics"]["height"] = m_resolution.y = 480; local["config"]["graphics"]["fullscreen"] = m_fullscreen = false; local["config"]["graphics"]["double_buffered"] = m_doubleBuffered = true; local["config"]["sound"]["sound_on"] = m_soundOn = true; local["config"]["sound"]["sound_volume"] = m_sfxVolume = MIX_MAX_VOLUME/2; local["config"]["sound"]["response_volume"] = m_responseVolume = 100; local["config"]["sound"]["voice_volume"] = m_voiceVolume = 128; local["config"]["sound"]["music_on"] = m_musicOn = true; local["config"]["sound"]["music_volume"] = m_musicVolume = MIX_MAX_VOLUME/2; local["config"]["sound"]["opl_emulator"] = m_emuOpl = (int)CT_EMUOPL; m_updated = true; } boost::filesystem::path pythonData(GetGameDir()); pythonData /= "python"; char *pyPath = Py_GetPath(); std::string pythonPath = pythonData.string() + #ifdef _WIN32 ";" #else ":" #endif + pyPath; PySys_SetPath((char*)pythonPath.c_str()); free(pyPath); save(); } catch(python::error_already_set const &) { PyErr_Print(); exit(EXIT_FAILURE); } #ifndef LOG_DISABLED Log::Instance()->setDefaultVerbosity(LogVerbosity(m_debug)); #endif /* if (configFile->exists("log_verbosity")) { Setting& node = configFile->lookup(".log_verbosity"); for (int j = 0; j < node.getLength(); j++) { std::string logSystem = node[j][0]; int logVerbosity = node[j][1]; Log::Instance()->setVerbosity(logSystem, (LogVerbosity)logVerbosity); } }*/ // Log::Instance()->setVerbosity("UnitClass", LV_MAX); // Log::Instance()->setVerbosity("ObjectClass", LV_MAX); // Log::Instance()->setVerbosity("TerrainClass", LV_MAX); // Log::Instance()->setVerbosity("MapClass", LV_MAX); /* root = configFile::loadFile((const char *)data); std::string config = ResMan::Instance()->readText("CONFIG:config.txt"); printf("%s\n", config.c_str()); config += "newline\n"; ResMan::Instance()->writeText("CONFIG:config.txt", config); */ }
int main( int argc, char ** argv ) { #if defined (FC_OS_LINUX) || defined(FC_OS_BSD) // Make sure to setup the Qt locale system before setting LANG and LC_ALL to C. // which is needed to use the system locale settings. (void)QLocale::system(); // http://www.freecadweb.org/tracker/view.php?id=399 // Because of setting LANG=C the Qt automagic to use the correct encoding // for file names is broken. This is a workaround to force the use of UTF-8 encoding QFile::setEncodingFunction(myEncoderFunc); QFile::setDecodingFunction(myDecoderFunc); // Make sure that we use '.' as decimal point. See also // http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=559846 putenv("LC_NUMERIC=C"); putenv("PYTHONPATH="); #elif defined(FC_OS_MACOSX) (void)QLocale::system(); putenv("LC_NUMERIC=C"); putenv("PYTHONPATH="); #else setlocale(LC_NUMERIC, "C"); _putenv("PYTHONPATH="); #endif #if defined (FC_OS_WIN32) int argc_ = argc; QVector<QByteArray> data; QVector<char *> argv_; // get the command line arguments as unicode string { QCoreApplication app(argc, argv); QStringList args = app.arguments(); for (QStringList::iterator it = args.begin(); it != args.end(); ++it) { data.push_back(it->toUtf8()); argv_.push_back(data.back().data()); } argv_.push_back(0); // 0-terminated string } #endif // Name and Version of the Application App::Application::Config()["ExeName"] = "FreeCAD"; App::Application::Config()["ExeVendor"] = "FreeCAD"; App::Application::Config()["AppDataSkipVendor"] = "true"; App::Application::Config()["MaintainerUrl"] = "http://www.freecadweb.org/wiki/index.php?title=Main_Page"; // set the banner (for logging and console) App::Application::Config()["CopyrightInfo"] = sBanner; App::Application::Config()["AppIcon"] = "freecad"; App::Application::Config()["SplashScreen"] = "freecadsplash"; App::Application::Config()["StartWorkbench"] = "StartWorkbench"; //App::Application::Config()["HiddenDockWindow"] = "Property editor"; App::Application::Config()["SplashAlignment" ] = "Bottom|Left"; App::Application::Config()["SplashTextColor" ] = "#ffffff"; // white App::Application::Config()["SplashInfoColor" ] = "#c8c8c8"; // light grey try { // Init phase =========================================================== // sets the default run mode for FC, starts with gui if not overridden in InitConfig... App::Application::Config()["RunMode"] = "Gui"; // Inits the Application #if defined (FC_OS_WIN32) App::Application::init(argc_, argv_.data()); #else App::Application::init(argc, argv); #endif #if defined(_MSC_VER) // create a dump file when the application crashes std::string dmpfile = App::Application::getUserAppDataDir(); dmpfile += "crash.dmp"; InitMiniDumpWriter(dmpfile); #endif std::map<std::string, std::string>::iterator it = App::Application::Config().find("NavigationStyle"); if (it != App::Application::Config().end()) { ParameterGrp::handle hGrp = App::GetApplication().GetParameterGroupByPath("User parameter:BaseApp/Preferences/View"); // if not already defined do it now (for the very first start) std::string style = hGrp->GetASCII("NavigationStyle", it->second.c_str()); hGrp->SetASCII("NavigationStyle", style.c_str()); } Gui::Application::initApplication(); // Only if 'RunMode' is set to 'Gui' do the replacement if (App::Application::Config()["RunMode"] == "Gui") Base::Interpreter().replaceStdOutput(); } catch (const Base::UnknownProgramOption& e) { QApplication app(argc,argv); QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str()); QString msg = QString::fromAscii(e.what()); QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>"); QMessageBox::critical(0, appName, s); exit(1); } catch (const Base::ProgramInformation& e) { QApplication app(argc,argv); QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str()); QString msg = QString::fromAscii(e.what()); QString s = QLatin1String("<pre>") + msg + QLatin1String("</pre>"); QMessageBox::information(0, appName, s); exit(0); } catch (const Base::Exception& e) { // Popup an own dialog box instead of that one of Windows QApplication app(argc,argv); QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str()); QString msg; msg = QObject::tr("While initializing %1 the following exception occurred: '%2'\n\n" "Python is searching for its files in the following directories:\n%3\n\n" "Python version information:\n%4\n") .arg(appName).arg(QString::fromUtf8(e.what())) .arg(QString::fromUtf8(Py_GetPath())).arg(QString::fromAscii(Py_GetVersion())); const char* pythonhome = getenv("PYTHONHOME"); if (pythonhome) { msg += QObject::tr("\nThe environment variable PYTHONHOME is set to '%1'.") .arg(QString::fromUtf8(pythonhome)); msg += QObject::tr("\nSetting this environment variable might cause Python to fail. " "Please contact your administrator to unset it on your system.\n\n"); } else { msg += QObject::tr("\nPlease contact the application's support team for more information.\n\n"); } QMessageBox::critical(0, QObject::tr("Initialization of %1 failed").arg(appName), msg); exit(100); } catch (...) { // Popup an own dialog box instead of that one of Windows QApplication app(argc,argv); QString appName = QString::fromAscii(App::Application::Config()["ExeName"].c_str()); QString msg = QObject::tr("Unknown runtime error occurred while initializing %1.\n\n" "Please contact the application's support team for more information.\n\n").arg(appName); QMessageBox::critical(0, QObject::tr("Initialization of %1 failed").arg(appName), msg); exit(101); } // Run phase =========================================================== Base::RedirectStdOutput stdcout; Base::RedirectStdLog stdclog; Base::RedirectStdError stdcerr; std::streambuf* oldcout = std::cout.rdbuf(&stdcout); std::streambuf* oldclog = std::clog.rdbuf(&stdclog); std::streambuf* oldcerr = std::cerr.rdbuf(&stdcerr); try { if (App::Application::Config()["RunMode"] == "Gui") Gui::Application::runApplication(); else App::Application::runApplication(); } catch (const Base::SystemExitException&) { exit(0); } catch (const Base::Exception& e) { Base::Console().Error("%s\n", e.what()); } catch (...) { Base::Console().Error("Application unexpectedly terminated\n"); } std::cout.rdbuf(oldcout); std::clog.rdbuf(oldclog); std::cerr.rdbuf(oldcerr); // Destruction phase =========================================================== Base::Console().Log("%s terminating...\n",App::Application::Config()["ExeName"].c_str()); // cleans up App::Application::destruct(); Base::Console().Log("%s completely terminated\n",App::Application::Config()["ExeName"].c_str()); return 0; }
PyObject* initializePython2(const std::vector<char*>& commandLineArgsUtf8) #endif { //See https://developer.blender.org/T31507 //Python will not load anything in site-packages if this is set //We are sure that nothing in system wide site-packages is loaded, for instance on OS X with Python installed //through macports on the system, the following printf show the following: /*Py_GetProgramName is /Applications/Natron.app/Contents/MacOS/Natron Py_GetPrefix is /Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7 Py_GetExecPrefix is /Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7 Py_GetProgramFullPath is /Applications/Natron.app/Contents/MacOS/Natron Py_GetPath is /Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python2.7:/Applications/Natron.app/Contents/MacOS/../Plugins:/Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python27.zip:/Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/:/Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin:/Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac:/Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages:/Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk:/Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old:/Applications/Natron.app/Contents/MacOS/../Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload Py_GetPythonHome is ../Frameworks/Python.framework/Versions/2.7/lib Python library is in /Applications/Natron.app/Contents/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages*/ //Py_NoSiteFlag = 1; ///////////////////////////////////////// // Py_SetProgramName ///////////////////////////////////////// // // Must be done before Py_Initialize (see doc of Py_Initialize) // #if PY_MAJOR_VERSION >= 3 // Python 3 Py_SetProgramName(commandLineArgsWide[0]); #else // Python 2 printf( "Py_SetProgramName(\"%s\")\n", commandLineArgsUtf8[0] ); Py_SetProgramName(commandLineArgsUtf8[0]); #endif ///////////////////////////////////////// // Py_Initialize ///////////////////////////////////////// // // Initialize the Python interpreter. In an application embedding Python, this should be called before using any other Python/C API functions; with the exception of Py_SetProgramName(), Py_SetPythonHome() and Py_SetPath(). #if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG) printf("Py_Initialize()\n"); #endif Py_Initialize(); // pythonHome must be const, so that the c_str() pointer is never invalidated ///////////////////////////////////////// // PySys_SetArgv ///////////////////////////////////////// // #if PY_MAJOR_VERSION >= 3 // Python 3 PySys_SetArgv( commandLineArgsWide.size(), const_cast<wchar_t**>(&commandLineArgsWide[0]) ); /// relative module import #else // Python 2 PySys_SetArgv( commandLineArgsUtf8.size(), const_cast<char**>(&commandLineArgsUtf8[0]) ); /// relative module import #endif PyObject* mainModule = PyImport_ImportModule("__main__"); //create main module , new ref //See http://wiki.blender.org/index.php/Dev:2.4/Source/Python/API/Threads //Python releases the GIL every 100 virtual Python instructions, we do not want that to happen in the middle of an expression. //_PyEval_SetSwitchInterval(LONG_MAX); //See answer for http://stackoverflow.com/questions/15470367/pyeval-initthreads-in-python-3-how-when-to-call-it-the-saga-continues-ad-naus PyEval_InitThreads(); ///Do as per http://wiki.blender.org/index.php/Dev:2.4/Source/Python/API/Threads ///All calls to the Python API should call PythonGILLocker beforehand. //_imp->mainThreadState = PyGILState_GetThisThreadState(); //PyEval_ReleaseThread(_imp->mainThreadState); std::string err; #if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG) /// print info about python lib { printf( "PATH is %s\n", Py_GETENV("PATH") ); printf( "PYTHONPATH is %s\n", Py_GETENV("PYTHONPATH") ); printf( "PYTHONHOME is %s\n", Py_GETENV("PYTHONHOME") ); printf( "Py_DebugFlag is %d\n", Py_DebugFlag ); printf( "Py_VerboseFlag is %d\n", Py_VerboseFlag ); printf( "Py_InteractiveFlag is %d\n", Py_InteractiveFlag ); printf( "Py_InspectFlag is %d\n", Py_InspectFlag ); printf( "Py_OptimizeFlag is %d\n", Py_OptimizeFlag ); printf( "Py_NoSiteFlag is %d\n", Py_NoSiteFlag ); printf( "Py_BytesWarningFlag is %d\n", Py_BytesWarningFlag ); printf( "Py_UseClassExceptionsFlag is %d\n", Py_UseClassExceptionsFlag ); printf( "Py_FrozenFlag is %d\n", Py_FrozenFlag ); printf( "Py_TabcheckFlag is %d\n", Py_TabcheckFlag ); printf( "Py_UnicodeFlag is %d\n", Py_UnicodeFlag ); printf( "Py_IgnoreEnvironmentFlag is %d\n", Py_IgnoreEnvironmentFlag ); printf( "Py_DivisionWarningFlag is %d\n", Py_DivisionWarningFlag ); printf( "Py_DontWriteBytecodeFlag is %d\n", Py_DontWriteBytecodeFlag ); printf( "Py_NoUserSiteDirectory is %d\n", Py_NoUserSiteDirectory ); printf( "Py_GetProgramName is %s\n", Py_GetProgramName() ); printf( "Py_GetPrefix is %s\n", Py_GetPrefix() ); printf( "Py_GetExecPrefix is %s\n", Py_GetPrefix() ); printf( "Py_GetProgramFullPath is %s\n", Py_GetProgramFullPath() ); printf( "Py_GetPath is %s\n", Py_GetPath() ); printf( "Py_GetPythonHome is %s\n", Py_GetPythonHome() ); PyObject* dict = PyModule_GetDict(mainModule); ///This is faster than PyRun_SimpleString since is doesn't call PyImport_AddModule("__main__") std::string script("from distutils.sysconfig import get_python_lib; print('Python library is in ' + get_python_lib())"); PyObject* v = PyRun_String(script.c_str(), Py_file_input, dict, 0); if (v) { Py_DECREF(v); } } #endif return mainModule; } // initializePython