Esempio n. 1
0
  PyInit() : m_pyFinalize(false) {
    if (!Py_IsInitialized()) {
#if PY_MAJOR_VERSION >= 3
      Py_SetPythonHome(const_cast<wchar_t *>(PYTHON_HOME_NAME));
#else
      Py_SetPythonHome(const_cast<char *>(PYTHON_HOME_NAME));
#endif
      Py_Initialize();
      PyEval_InitThreads();
      m_pyFinalize = true;
    }
    numpy_init();
  }
Esempio n. 2
0
PythonModules::PythonModules(QString name, Pip3lineCallback *callback) :
    ModulesManagement(name, PYTHON_EXTENSION, BASE_SCRIPTS_DIR, callback)
{

    pyGetValFunc = nullptr;
    pyStringIO = nullptr;
    pyTruncateFunc = nullptr;
    pySeekFunc = nullptr;

    Py_SetProgramName(PROG_NAME);
    Py_DontWriteBytecodeFlag++;

#if defined(Q_OS_WIN) && !defined(BUILD_PYTHON_3)
    pythonPath = PythonModules::initPythonPath();
    Py_SetPythonHome(pythonPath);
#endif //Q_OS_WIN && !BUILD_PYTHON_3

    // initialize the Python interpreter without signal handler
    Py_InitializeEx(0);
    // initialize thread support
    PyEval_InitThreads();
    // saving thread state
    pymainstate = PyEval_SaveThread();

   connect(this, &PythonModules::pathsUpdated, this, &PythonModules::updatePath);
   qDebug() << "Created " << this;

}
Esempio n. 3
0
/* Initialize Python interpreter */
static void python_system_init(lua_State *L) {
    char *python_home = luaL_check_string(L, 1);

    if (!Py_IsInitialized()) {
        PyObject *luam, *mainm, *maind;
#if PY_MAJOR_VERSION >= 3
        wchar_t *argv[] = {L"<lua>", 0};
#else
        char *argv[] = {"<lua>", 0};
#endif
        Py_SetProgramName(argv[0]);
        Py_SetPythonHome(python_home);
        Py_Initialize();
        PySys_SetArgv(1, argv);
        /* Import 'lua' automatically. */
        luam = PyImport_ImportModule("lua");
        if (!luam) {
            lua_error(L, "Can't import lua module");
        } else {
            mainm = PyImport_AddModule("__main__");
            if (!mainm) {
                lua_error(L, "Can't get __main__ module");
            } else {
                maind = PyModule_GetDict(mainm);
                PyDict_SetItemString(maind, "lua", luam);
                Py_DECREF(luam);
            }
        }
    }
}
Esempio n. 4
0
    static int
Python_Init(void)
{
    if (!initialised)
    {
#ifdef DYNAMIC_PYTHON
	if (!python_enabled(TRUE))
	{
	    EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
	    goto fail;
	}
#endif

#ifdef PYTHON_HOME
	Py_SetPythonHome(PYTHON_HOME);
#endif

	init_structs();

#if !defined(MACOS) || defined(MACOS_X_UNIX)
	Py_Initialize();
#else
	PyMac_Initialize();
#endif
	/* initialise threads */
	PyEval_InitThreads();

#ifdef DYNAMIC_PYTHON
	get_exceptions();
#endif

	if (PythonIO_Init())
	    goto fail;

	if (PythonMod_Init())
	    goto fail;

	/* Remove the element from sys.path that was added because of our
	 * argv[0] value in PythonMod_Init().  Previously we used an empty
	 * string, but dependinding on the OS we then get an empty entry or
	 * the current directory in sys.path. */
	PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");

	/* the first python thread is vim's, release the lock */
	Python_SaveThread();

	initialised = 1;
    }

    return 0;

fail:
    /* We call PythonIO_Flush() here to print any Python errors.
     * This is OK, as it is possible to call this function even
     * if PythonIO_Init() has not completed successfully (it will
     * not do anything in this case).
     */
    PythonIO_Flush();
    return -1;
}
Esempio n. 5
0
/* Initialize Python interpreter */
static void python_system_init(lua_State *L) {
    char *python_home = luaL_check_string(L, 1);
    if (!Py_IsInitialized()) {
        python_setnumber(L, PY_API_IS_EMBEDDED, 1); // If python is inside Lua
        if (PyType_Ready(&LuaObject_Type) == 0) {
            Py_INCREF(&LuaObject_Type);
        } else {
            lua_error(L, "failure initializing lua object type");
        }
        PyObject *luam, *mainm, *maind;
#if PY_MAJOR_VERSION >= 3
        wchar_t *argv[] = {L"<lua_bootstrap>", 0};
#else
        char *argv[] = {"<lua_bootstrap>", 0};
#endif
        Py_SetProgramName(argv[0]);
        Py_SetPythonHome(python_home);
        Py_InitializeEx(0);
        PySys_SetArgv(1, argv);
        /* Import 'lua' automatically. */
        luam = PyImport_ImportModule("lua_bootstrap");
        if (!luam) {
            lua_error(L, "Can't import lua_bootstrap module");
        } else {
            mainm = PyImport_AddModule("__main__");
            if (!mainm) {
                lua_error(L, "Can't get __main__ module");
            } else {
                maind = PyModule_GetDict(mainm);
                PyDict_SetItemString(maind, "lua_bootstrap", luam);
                Py_DECREF(luam);
            }
        }
    }
}
Esempio n. 6
0
bool EmbedPython::init()
{

    if(initialized)
        return true;

    /** Setting Python folder */
    QDir dir(qApp->applicationDirPath());
    //
    QString p = QString("python27");
    py_progname = p.toLocal8Bit();

#if __APPLE__
    dir.cdUp();
    dir.cd("Resources");
    dir.cd("site-packages");
#endif

    p = dir.absolutePath();// + dir.separator() + QString("embed");

    py_pythonhome = p.toLocal8Bit();
    //QMessageBox::warning(NULL, "", p);

#if !__APPLE__
    Py_SetProgramName(py_progname.data());
//    qDebug()<<"program path:"<<Py_GetProgramFullPath();
//    qDebug()<<"program name:"<<Py_GetProgramName();
//    qDebug()<<"python path:"<<Py_GetPath() ;
    Py_SetPythonHome(py_pythonhome.data());
#endif
//    qDebug()<<"program home:"<<Py_GetPythonHome();
//    qDebug()<<"program path:"<<Py_GetProgramFullPath();
//    qDebug()<<"program name:"<<Py_GetProgramName();
//    qDebug()<<"python path:"<<Py_GetPath() ;
//    QMessageBox::warning(NULL, "", Py_GetPath());
    /** Initialize Python */
    Py_InitializeEx(0);
    //Py_Initialize();
    if(Py_IsInitialized() != 0) {
        initialized = true;
        //globals = PyList_New(0);
        //locals = PyList_New(0);
//        PyObject* fromlist = PyList_New(1);
//        PyList_SET_ITEM(fromlist, 0, PyString_FromString("*"));
        /** Import main module */
//        char mname[512];
//        memset(mname, 0, 512);
//        memcpy(mname, "__main__", sizeof("__main__"));
//        mainmodel = PyImport_ImportModuleEx(mname, globals, locals, fromlist);
//        checkError();
        /** Import modeltool module */
//        memset(mname, 0, 512);
//        memcpy(mname, MODELTOOL, sizeof(MODELTOOL));
        //modeltool = PyImport_ImportModuleEx(mname, globals, locals, fromlist);
        QString cmd = QString("import sys; import os;  sys.path.append(os.path.abspath('%1'))")
#if __APPLE__
                .arg(dir.absolutePath());
#else
                .arg(qApp->applicationDirPath());
Esempio n. 7
0
File: util.c Progetto: AEliu/calibre
void initialize_interpreter(const char **ENV_VARS, const char **ENV_VAR_VALS,
        char *PROGRAM, const char *MODULE, const char *FUNCTION, const char *PYVER, int IS_GUI,
        const char* exe_path, const char *rpath, int argc, const char **argv) {
    PyObject *pargv, *v;
    int i;
    Py_OptimizeFlag = 2;
    Py_NoSiteFlag = 1;
    Py_DontWriteBytecodeFlag = 1;
    Py_IgnoreEnvironmentFlag = 1;
    Py_NoUserSiteDirectory = 1;
    Py_HashRandomizationFlag = 1;

    //Py_VerboseFlag = 1;
    //Py_DebugFlag = 1;
    
    Py_SetProgramName(PROGRAM);

    char pyhome[1000];
    snprintf(pyhome, 1000, "%s/Python", rpath);
    Py_SetPythonHome(pyhome);

    set_env_vars(ENV_VARS, ENV_VAR_VALS, exe_path);

    //printf("Path before Py_Initialize(): %s\r\n\n", Py_GetPath());
    Py_Initialize();

    char *dummy_argv[1] = {""};
    PySys_SetArgv(1, dummy_argv);
    //printf("Path after Py_Initialize(): %s\r\n\n", Py_GetPath());
    char path[3000];
    snprintf(path, 3000, "%s/lib/python%s:%s/lib/python%s/lib-dynload:%s/site-packages", pyhome, PYVER, pyhome, PYVER, pyhome);

    PySys_SetPath(path);
    //printf("Path set by me: %s\r\n\n", path);

    PySys_SetObject("calibre_basename", PyBytes_FromString(PROGRAM));
    PySys_SetObject("calibre_module", PyBytes_FromString(MODULE));
    PySys_SetObject("calibre_function", PyBytes_FromString(FUNCTION));
    PySys_SetObject("calibre_is_gui_app", ((IS_GUI) ? Py_True : Py_False));
    PySys_SetObject("resourcepath", PyBytes_FromString(rpath));
    snprintf(path, 3000, "%s/site-packages", pyhome);
    PySys_SetObject("site_packages", PyBytes_FromString(pyhome));


    pargv = PyList_New(argc);
    if (pargv == NULL) exit(report_error(ERR_OOM));
    for (i = 0; i < argc; i++) {
        v = PyBytes_FromString(argv[i]);
        if (v == NULL) exit(report_error(ERR_OOM));
        PyList_SetItem(pargv, i, v);
    }
    PySys_SetObject("argv", pargv);

}
Esempio n. 8
0
void CGEPYManager::InitDll()
{
	if ( m_bInit )
		return;

	try
	{
		char filePath[255];
		filesystem->RelativePathToFullPath(GetRootPath(), "MOD", filePath, sizeof(filePath) );
		Py_SetPythonHome(filePath);

		RegisterPythonModules();
		Py_Initialize();

		main_module = bp::import("__main__");
		main_namespace = main_module.attr("__dict__");

		main_module.attr("true") = true;
		main_module.attr("false") = false;

		try
		{
			ExecFile("IORedirect.py");
		}
		catch (...)
		{
			HandlePythonException();
		}

#if defined (WINGDBG) && (DEBUG)
		try
		{
			Exec("import wingdbstub");
		}
		catch (...)
		{
			Warning("Failed to import python debugger\n");
			HandlePythonException();
		}
#endif		
		

		m_bInit = true;
	}
	catch (...)
	{
		HandlePythonException();
		Warning("Failed to load python. :(\n");
	}
}
Esempio n. 9
0
	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());
	}
Esempio n. 10
0
    PythonEngine( wchar_t *pypath )
	    : m_global_dict( nullptr )
    {
		assert__( pypath );

        Py_SetPythonHome( pypath );

        Py_InitializeEx( 0 );

        // Get a reference to the main module and global dictionary
        //
        PyObject *main_module = PyImport_AddModule("__main__");
        if (main_module)
            m_global_dict = PyModule_GetDict( main_module );
    }
Esempio n. 11
0
int main(int argc, char *argv[])
{
    int err;

#ifdef __WIN32__
    //Let's make sure we're in the directory where the executable
    //is since this is required for Makehuman to function on Windows
    //Makehuman will fail to start if you're not in the same directory
    //as the executable
    TCHAR exepath[MAX_PATH];
    if (0 == GetModuleFileName(0, exepath, MAX_PATH)) {
	fprintf(stderr, "coulnd't get executable path\n");
    }
    else {
	PathRemoveFileSpec(exepath);
	SetCurrentDirectory(exepath);
    }
#endif

    Py_SetProgramName(argv[0]);
#if 0
    Py_SetPythonHome(".");
#endif
    Py_Initialize();

    if (!Py_IsInitialized())
    {
        fprintf(stderr, "Could not initialize Python\n");
        exit(EXIT_FAILURE);
    }

    PySys_SetArgv(argc, argv);

    PyEval_InitThreads();

    err = PyRun_SimpleString("execfile('makehuman.py')");

    if (err != 0)
    {
        fprintf(stderr, "Could not run main Python script\n");
        getchar();
        exit(EXIT_FAILURE);
    }

    Py_Finalize();

    return 0;
}
Esempio n. 12
0
int main()
{
    LPWSTR *szArglist;
    int nArgs;
    wchar_t wszPath[10240];
    wchar_t wszCmd[10240];
    wchar_t *p;
    char* szCmd;

    GetModuleFileNameW(NULL, wszPath, sizeof(wszPath));
    p = wcsrchr(wszPath, L'\\');
    if (p == NULL) {
            printf("Get module file name error!\n");
            return -1;
    }
    *p = 0;

    szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);

    swprintf(wszCmd, L"PATH=%s\\DLLs;%%PATH%%", wszPath);
    _wputenv(wszCmd);

    Py_NoSiteFlag = 1;
    Py_SetPythonHome(wszPath);
    swprintf(wszCmd, L"%s\\Lib", wszPath);
    Py_SetPath(wszCmd);
    Py_Initialize();
    PySys_SetArgv(nArgs-1, szArglist+1);

    swprintf(wszCmd,
            L"import sys\n"
            L"cur = r'%s'\n"
            L"join = lambda *args: '\\\\'.join(args)\n"
            L"sys.path = [join(cur, f) for f in ['', 'Lib', 'Lib/libstdpy.zip', 'site-packages', 'DLLs']]\n"
            L"import os; join = os.path.join\n"
            L"sys.path += [join(cur, 'Lib', f) for f in os.listdir(join(cur, 'Lib')) if f.endswith('.zip') and f != 'libstdpy.zip']\n"
            L"sys.path.insert(1, join(cur, 'src.zip'))\n"
            L"m = r'%s'\n"
            L"sys.path.insert(0, os.path.split(m)[0])\n"
            L"import imp; imp.load_source('__main__', m)\n",
            wszPath, *(szArglist+1));
    /* wprintf(wszCmd); */
    szCmd = to_utf8(wszCmd);
    PyRun_SimpleString(szCmd);
    free(szCmd);
    LocalFree(szArglist);
    return 0;
}
Esempio n. 13
0
void setHome(std::string dir)
{
    if(!Py_IsInitialized())
    {
        if (::fwPython::Config::home)
        {
            delete [] ::fwPython::Config::home;
        }

        ::fwPython::Config::home = charFromString(dir);

        Py_SetPythonHome( ::fwPython::Config::home );
        OSLM_INFO("Python Home set to " << dir);
    }
    SLM_ERROR_IF("Python home must be set before python initialisation", Py_IsInitialized());
}
Esempio n. 14
0
PythonScriptInterface::PythonScriptInterface(CHCGameServer *gameserver) : IScriptInterface(gameserver) {
  gbl_pi_interface = this;
  mp_current_info_table = NULL;

  PyImport_AppendInittab("CoreServer", PyInit_CoreServer);
  PyImport_AppendInittab("Frontend", PyInit_FrontEnd);
  PyImport_AppendInittab("SAMP", PyInit_SAMP);

  Py_SetPythonHome(L"E:\\Code\\Python-3.5.0"); //temp windows fix

  Py_Initialize();
  FILE *fd = fopen("scripts/__init__.py", "rb");
  PyRun_AnyFile(fd, NULL);
  fclose(fd);
 
}
Esempio n. 15
0
int setup_py() {
	//mprintf ( _T("Setup Python: \n"));
	//mprintf ( char2wchar_t(PY_HOME) );
	if (PY_HOME!=NULL){
		//mprintf ( _T("Path given: "));
		// Set Python executable path and Python HOME path to be used
		char* PY_EXECUTABLE = combine(PY_HOME,"\\python.exe");
		//mprintf ( char2wchar_t(PY_EXECUTABLE) );
		Py_SetProgramName(PY_EXECUTABLE);
		Py_SetPythonHome(PY_HOME);
		}
	//else {mprintf ( _T("\nPath NOT exists \n"));}

	// Initialize python
	Py_Initialize();
	return 0;
	}
Esempio n. 16
0
/* must be called before Py_Initialize, expects output of BLI_get_folder(BLENDER_PYTHON, NULL) */
void PyC_SetHomePath(const char *py_path_bundle)
{
	if(py_path_bundle==NULL) {
		/* Common enough to have bundled *nix python but complain on OSX/Win */
#if defined(__APPLE__) || defined(_WIN32)
		fprintf(stderr, "Warning! bundled python not found and is expected on this platform. (if you built with CMake: 'install' target may have not been built)\n");
#endif
		return;
	}
	/* set the environment path */
	printf("found bundled python: %s\n", py_path_bundle);

#ifdef __APPLE__
	/* OSX allow file/directory names to contain : character (represented as / in the Finder)
	 but current Python lib (release 3.1.1) doesn't handle these correctly */
	if(strchr(py_path_bundle, ':'))
		printf("Warning : Blender application is located in a path containing : or / chars\
			   \nThis may make python import function fail\n");
#endif

#ifdef _WIN32
	/* cmake/MSVC debug build crashes without this, why only
	   in this case is unknown.. */
	{
		BLI_setenv("PYTHONPATH", py_path_bundle);
	}
#endif

	{
		static wchar_t py_path_bundle_wchar[1024];

		/* cant use this, on linux gives bug: #23018, TODO: try LANG="en_US.UTF-8" /usr/bin/blender, suggested 22008 */
		/* mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR); */

		utf8towchar(py_path_bundle_wchar, py_path_bundle);

		Py_SetPythonHome(py_path_bundle_wchar);
		// printf("found python (wchar_t) '%ls'\n", py_path_bundle_wchar);
	}
}
Esempio n. 17
0
int main(int argc, char *argv[])
{
    Py_SetProgramName(argv[0]);
    Py_SetPythonHome("C:/Python27");
    Py_Initialize();
    initmymath(); //REMEMBER!!

    PyObject* pName = PyString_FromString("__main__");
    PyObject* pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    
    PyRun_SimpleString("import mymath");
    PyRun_SimpleString("def simple_log(msg):\n"
                       "    print 'Log ', msg2\n\n"
                       "mymath.reg_log(simple_log)\n");
    PyRun_SimpleString("def add(a, b):\n"
                       "    return mymath.add(a, b)\n");

    PyObject* pFunc = PyObject_GetAttrString(pModule,
                                             "add");
    PyObject* pArgs = PyTuple_New(2);
    PyObject* param1 = PyFloat_FromDouble(2.1);
    PyTuple_SetItem(pArgs, 0, param1);
    PyObject* param2 = PyFloat_FromDouble(3.2);
    PyTuple_SetItem(pArgs, 1, param2);

    PyObject* pValue = PyObject_CallObject(pFunc, pArgs);
    Py_DECREF(pArgs);
    if(pValue==NULL)
        printf("Call failed\n");
    else{
        printf("Result of call: %lf\n",
               PyFloat_AsDouble(pValue));
        Py_XDECREF(pValue);  
    }
        
    Py_Finalize();
    return 0;
}
Esempio n. 18
0
// 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;
}
Esempio n. 19
0
    static int
Python_Init(void)
{
    if (!initialised)
    {
#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
	PyObject *site;
#endif

#ifdef DYNAMIC_PYTHON
	if (!python_enabled(TRUE))
	{
	    EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
	    goto fail;
	}
#endif

#ifdef PYTHON_HOME
# ifdef DYNAMIC_PYTHON
	if (mch_getenv((char_u *)"PYTHONHOME") == NULL)
# endif
	    Py_SetPythonHome(PYTHON_HOME);
#endif

	init_structs();

#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
	/* Disable implicit 'import site', because it may cause Vim to exit
	 * when it can't be found. */
	Py_NoSiteFlag++;
#endif

#if !defined(MACOS) || defined(MACOS_X_UNIX)
	Py_Initialize();
#else
	PyMac_Initialize();
#endif

#if defined(PY_VERSION_HEX) && PY_VERSION_HEX >= 0x02070000
	/* 'import site' explicitly. */
	site = PyImport_ImportModule("site");
	if (site == NULL)
	{
	    EMSG(_("E887: Sorry, this command is disabled, the Python's site module could not be loaded."));
	    goto fail;
	}
	Py_DECREF(site);
#endif

	/* Initialise threads, and below save the state using
	 * PyEval_SaveThread.  Without the call to PyEval_SaveThread, thread
	 * specific state (such as the system trace hook), will be lost
	 * between invocations of Python code. */
	PyEval_InitThreads();
#ifdef DYNAMIC_PYTHON
	get_exceptions();
#endif

	if (PythonIO_Init_io())
	    goto fail;

	if (PythonMod_Init())
	    goto fail;

	globals = PyModule_GetDict(PyImport_AddModule("__main__"));

	/* Remove the element from sys.path that was added because of our
	 * argv[0] value in PythonMod_Init().  Previously we used an empty
	 * string, but depending on the OS we then get an empty entry or
	 * the current directory in sys.path. */
	PyRun_SimpleString("import sys; sys.path = filter(lambda x: x != '/must>not&exist', sys.path)");

	/* lock is created and acquired in PyEval_InitThreads() and thread
	 * state is created in Py_Initialize()
	 * there _PyGILState_NoteThreadState() also sets gilcounter to 1
	 * (python must have threads enabled!)
	 * so the following does both: unlock GIL and save thread state in TLS
	 * without deleting thread state
	 */
#ifndef PY_CAN_RECURSE
	saved_python_thread =
#endif
	    PyEval_SaveThread();

	initialised = 1;
    }

    return 0;

fail:
    /* We call PythonIO_Flush() here to print any Python errors.
     * This is OK, as it is possible to call this function even
     * if PythonIO_Init_io() has not completed successfully (it will
     * not do anything in this case).
     */
    PythonIO_Flush();
    return -1;
}
Esempio n. 20
0
int AppMain()
{
	std::wstring exe_dir;

	// Get exe's directory
	{
		wchar_t exe_path_buf[MAX_PATH + 1];
		GetModuleFileName(NULL, exe_path_buf, MAX_PATH);

		exe_dir = exe_path_buf;

		size_t last_backslash_pos = exe_dir.find_last_of(L"\\/");
		if (last_backslash_pos >= 0)
		{
			exe_dir = exe_dir.substr(0, last_backslash_pos);
		}
		else
		{
			exe_dir = L"";
		}
	}

	// Setup environment variable "PATH"
	{
		std::wstring env_path;

		wchar_t tmp_buf[1];
		DWORD ret = GetEnvironmentVariable(L"PATH", tmp_buf, 0);
		if (ret > 0)
		{
			DWORD len = ret;
			wchar_t * buf = (wchar_t*)malloc((len + 1) * sizeof(wchar_t));

			GetEnvironmentVariable(L"PATH", buf, (len + 1) * sizeof(wchar_t));

			env_path = buf;

			free(buf);
		}

		env_path = exe_dir + L"/lib;" + env_path;

		SetEnvironmentVariable(L"PATH", env_path.c_str());
	}

	// Python home
	{
#if defined(_DEBUG)
		Py_SetPythonHome(PYTHON_INSTALL_PATH);
#else
		Py_SetPythonHome(const_cast<wchar_t*>(exe_dir.c_str()));
#endif //_DEBUG
	}

	// Python module search path
	{
		std::wstring python_path;

		python_path += exe_dir + L"/extension;";
		
		#if defined(_DEBUG)
		python_path += exe_dir + L";";
		python_path += exe_dir + L"/..;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\Lib\\site-packages;";
		python_path += std::wstring(PYTHON_INSTALL_PATH) + L"\\DLLs;";
		#else
		python_path += exe_dir + L"/library.zip;";
		python_path += exe_dir + L"/lib;";
		#endif
		
		Py_SetPath(python_path.c_str());
	}

	// Initialization
	Py_Initialize();

	// Setup sys.argv
	{
		wchar_t * cmdline = GetCommandLine();

		int argc;
		wchar_t ** argv = CommandLineToArgvW(cmdline, &argc);

		PySys_SetArgv(argc, argv);

		LocalFree(argv);
	}

	// Execute python side main script
	{
		PyObject * module = PyImport_ImportModule("cfiler_main");
		if (module == NULL)
		{
			PyErr_Print();
		}

		Py_XDECREF(module);
		module = NULL;
	}

	// Termination
	Py_Finalize();

	return 0;
}
Esempio n. 21
0
//-------------------------------------------------------------------------------------
bool Script::install(const wchar_t* pythonHomeDir, std::wstring pyPaths, 
	const char* moduleName, COMPONENT_TYPE componentType)
{
	std::wstring pySysPaths = SCRIPT_PATH;
	wchar_t* pwpySysResPath = strutil::char2wchar(const_cast<char*>(Resmgr::getSingleton().getPySysResPath().c_str()));
	strutil::kbe_replace(pySysPaths, L"../../res/", pwpySysResPath);
	pyPaths += pySysPaths;
	free(pwpySysResPath);

#if KBE_PLATFORM == PLATFORM_WIN32
	Py_SetPythonHome(const_cast<wchar_t*>(pythonHomeDir));								// 先设置python的环境变量
#else
	std::wstring fs = L";";
	std::wstring rs = L":";
	size_t pos = 0; 

	while(true)
	{ 
		pos = pyPaths.find(fs, pos);
		if (pos == std::wstring::npos) break;
		pyPaths.replace(pos, fs.length(), rs);
	}  

	Py_SetPath(pyPaths.c_str()); 
	char* tmpchar = strutil::wchar2char(const_cast<wchar_t*>(pyPaths.c_str()));
	DEBUG_MSG(boost::format("Script::install: paths=%1%.\n") % tmpchar);
	free(tmpchar);
	
#endif
	// Initialise python
	// Py_VerboseFlag = 2;
	Py_FrozenFlag = 1;

	// Warn if tab and spaces are mixed in indentation.
	// Py_TabcheckFlag = 1;
	Py_NoSiteFlag = 1;
	Py_IgnoreEnvironmentFlag = 1;
	Py_Initialize();                      											// python解释器的初始化  
    if (!Py_IsInitialized())
    {
    	ERROR_MSG("Script::install::Py_Initialize is failed!\n");
        return false;
    } 

#if KBE_PLATFORM == PLATFORM_WIN32
	PySys_SetPath(pyPaths.c_str());
#endif

	PyObject *m = PyImport_AddModule("__main__");

	module_ = PyImport_AddModule(moduleName);										// 添加一个脚本基础模块
	if (module_ == NULL)
		return false;
	
	const char* componentName = COMPONENT_NAME_EX(componentType);
	if (PyModule_AddStringConstant(module_, "component", componentName))
	{
		ERROR_MSG(boost::format("Script::init: Unable to set KBEngine.component to %1%\n") %
			componentName );
		return false;
	}
	
	// 注册产生uuid方法到py
	APPEND_SCRIPT_MODULE_METHOD(module_,		genUUID64,			__py_genUUID64,					METH_VARARGS,			0);

	if(!install_py_dlls())
	{
		ERROR_MSG("Script::init: install_py_dlls() is failed!\n");
		return false;
	}

#ifndef KBE_SINGLE_THREADED
	s_pOurInitTimeModules = PyDict_Copy( PySys_GetObject( "modules" ) );
	s_pMainThreadState = PyThreadState_Get();
	s_defaultContext = s_pMainThreadState;
	PyEval_InitThreads();

	KBEConcurrency::setMainThreadIdleFunctions(
		&Script::releaseLock, &Script::acquireLock );
#endif

	ScriptStdOutErr::installScript(NULL);											// 安装py重定向模块
	ScriptStdOutErrHook::installScript(NULL);

	static struct PyModuleDef moduleDesc =   
	{  
			 PyModuleDef_HEAD_INIT,  
			 moduleName,  
			 "This module is created by KBEngine!",  
			 -1,  
			 NULL  
	};  

	PyModule_Create(&moduleDesc);													// 初始化基础模块
	PyObject_SetAttrString(m, moduleName, module_);									// 将模块对象加入main

	pyStdouterr_ = new ScriptStdOutErr();											// 重定向python输出
	pyStdouterrHook_ = new ScriptStdOutErrHook();
	
	if(!pyStdouterr_->install()){													// 安装py重定向脚本模块
		ERROR_MSG("Script::install::pyStdouterr_->install() is failed!\n");
		SCRIPT_ERROR_CHECK();
		return false;
	}
	
	Pickler::initialize();
	PyProfile::initialize(this);
	PyStruct::initialize();
	Copy::initialize();
	SCRIPT_ERROR_CHECK();

	math::installModule("Math");
	INFO_MSG("Script::install is successfully!\n");
	return installExtraModule("KBExtra");
}
Esempio n. 22
0
static int
Python3_Init(void)
{
	if (!py3initialised) {
#ifdef DYNAMIC_PYTHON3
		if (!python3_enabled(TRUE)) {
			EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded."));
			goto fail;
		}
#endif

		init_structs();


#ifdef PYTHON3_HOME
		Py_SetPythonHome(PYTHON3_HOME);
#endif

		PyImport_AppendInittab("vim", Py3Init_vim);

#if !defined(MACOS) || defined(MACOS_X_UNIX)
		Py_Initialize();
#else
		PyMac_Initialize();
#endif
		/* Initialise threads, and below save the state using
		 * PyEval_SaveThread.  Without the call to PyEval_SaveThread, thread
		 * specific state (such as the system trace hook), will be lost
		 * between invocations of Python code. */
		PyEval_InitThreads();
#ifdef DYNAMIC_PYTHON3
		get_py3_exceptions();
#endif

		if (PythonIO_Init_io())
			goto fail;

		globals = PyModule_GetDict(PyImport_AddModule("__main__"));

		/* Remove the element from sys.path that was added because of our
		 * argv[0] value in Py3Init_vim().  Previously we used an empty
		 * string, but depending on the OS we then get an empty entry or
		 * the current directory in sys.path.
		 * Only after vim has been imported, the element does exist in
		 * sys.path.
		 */
		PyRun_SimpleString("import vim; import sys; sys.path = list(filter(lambda x: not x.endswith('must>not&exist'), sys.path))");

		/* lock is created and acquired in PyEval_InitThreads() and thread
		 * state is created in Py_Initialize()
		 * there _PyGILState_NoteThreadState() also sets gilcounter to 1
		 * (python must have threads enabled!)
		 * so the following does both: unlock GIL and save thread state in TLS
		 * without deleting thread state
		 */
		PyEval_SaveThread();

		py3initialised = 1;
	}

	return 0;

fail:
	/* We call PythonIO_Flush() here to print any Python errors.
	 * This is OK, as it is possible to call this function even
	 * if PythonIO_Init_io() has not completed successfully (it will
	 * not do anything in this case).
	 */
	PythonIO_Flush();
	return -1;
}
Esempio n. 23
0
void setupPythonEnv(const char* argv0Param)
{
    //Disable user sites as they could conflict with Natron bundled packages.
    //If this is set, Python won’t add the user site-packages directory to sys.path.
    //See https://www.python.org/dev/peps/pep-0370/
    ProcInfo::putenv_wrapper("PYTHONNOUSERSITE", "1");
    ++Py_NoUserSiteDirectory;

    //
    // set up paths, clear those that don't exist or are not valid
    //
    std::string binPath = ProcInfo::applicationDirPath(argv0Param);
    binPath = StrUtils::toNativeSeparators(binPath);
#ifdef __NATRON_WIN32__
    static std::string pythonHome = binPath + "\\.."; // must use static storage
    std::string pyPathZip = pythonHome + "\\lib\\python" NATRON_PY_VERSION_STRING_NO_DOT ".zip";
    std::string pyPath = pythonHome +  "\\lib\\python" NATRON_PY_VERSION_STRING;
    std::string pluginPath = binPath + "\\..\\Plugins";
#else
#  if defined(__NATRON_LINUX__)
    static std::string pythonHome = binPath + "/.."; // must use static storage
#  elif defined(__NATRON_OSX__)
    static std::string pythonHome = binPath+ "/../Frameworks/Python.framework/Versions/" NATRON_PY_VERSION_STRING; // must use static storage
#  else
#    error "unsupported platform"
#  endif
    std::string pyPathZip = pythonHome + "/lib/python" NATRON_PY_VERSION_STRING_NO_DOT ".zip";
    std::string pyPath = pythonHome + "/lib/python" NATRON_PY_VERSION_STRING;
    std::string pluginPath = binPath + "/../Plugins";
#endif
    if ( !fileExists( StrUtils::fromNativeSeparators(pyPathZip) ) ) {
#     if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG)
        printf( "\"%s\" does not exist, not added to PYTHONPATH\n", pyPathZip.c_str() );
#     endif
        pyPathZip.clear();
    }
    if ( !dirExists( StrUtils::fromNativeSeparators(pyPath) ) ) {
#     if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG)
        printf( "\"%s\" does not exist, not added to PYTHONPATH\n", pyPath.c_str() );
#     endif
        pyPath.clear();
    }
    if ( !dirExists( StrUtils::fromNativeSeparators(pluginPath) ) ) {
#     if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG)
        printf( "\"%s\" does not exist, not added to PYTHONPATH\n", pluginPath.c_str() );
#     endif
        pluginPath.clear();
    }
    // PYTHONHOME is really useful if there's a python inside it
    if ( pyPathZip.empty() && pyPath.empty() ) {
#     if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG)
        printf( "dir \"%s\" does not exist or does not contain lib/python*, not setting PYTHONHOME\n", pythonHome.c_str() );
#     endif
        pythonHome.clear();
    }

    /////////////////////////////////////////
    // Py_SetPythonHome
    /////////////////////////////////////////
    //
    // Must be done before Py_Initialize (see doc of Py_Initialize)
    //
    // The argument should point to a zero-terminated character string in static storage whose contents will not change for the duration of the program’s execution

    if ( !pythonHome.empty() ) {
#     if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG)
        printf( "Py_SetPythonHome(\"%s\")\n", pythonHome.c_str() );
#     endif
#     if PY_MAJOR_VERSION >= 3
        // Python 3
        static const std::wstring pythonHomeW = StrUtils::utf8_to_utf16(pythonHome); // must use static storage
        Py_SetPythonHome( const_cast<wchar_t*>( pythonHomeW.c_str() ) );
#     else
        // Python 2
        Py_SetPythonHome( const_cast<char*>( pythonHome.c_str() ) );
#     endif
    }


    /////////////////////////////////////////
    // PYTHONPATH and Py_SetPath
    /////////////////////////////////////////
    //
    // note: to check the python path of a python install, execute:
    // python -c 'import sys,pprint; pprint.pprint( sys.path )'
    //
    // to build the python27.zip, cd to lib/python2.7, and generate the pyo and the zip file using:
    //
    //  python -O -m compileall .
    //  zip -r ../python27.zip *.py* bsddb compiler ctypes curses distutils email encodings hotshot idlelib importlib json logging multiprocessing pydoc_data sqlite3 unittest wsgiref xml
    //
    std::string pythonPath = ProcInfo::getenv_wrapper("PYTHONPATH");
    //Add the Python distribution of Natron to the Python path

    std::vector<std::string> toPrepend;
    if ( !pyPathZip.empty() ) {
        toPrepend.push_back(pyPathZip);
    }
    if ( !pyPath.empty() ) {
        toPrepend.push_back(pyPath);
    }
    if ( !pluginPath.empty() ) {
        toPrepend.push_back(pluginPath);
    }

#if defined(__NATRON_OSX__) && defined DEBUG
    // in debug mode, also prepend the local PySide directory
    // homebrew's pyside directory
    toPrepend.push_back("/usr/local/Cellar/pyside/1.2.2_1/lib/python" NATRON_PY_VERSION_STRING "/site-packages");
    // macport's pyside directory
    toPrepend.push_back("/opt/local/Library/Frameworks/Python.framework/Versions/" NATRON_PY_VERSION_STRING "/lib/python" NATRON_PY_VERSION_STRING "/site-packages");
#endif

    if ( toPrepend.empty() ) {
#     if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG)
        printf("PYTHONPATH not modified\n");
#     endif
    } else {
#     ifdef __NATRON_WIN32__
        const char pathSep = ';';
#     else
        const char pathSep = ':';
#     endif
        std::string toPrependStr = StrUtils::join(toPrepend, pathSep);
        if (pythonPath.empty()) {
            pythonPath = toPrependStr;
        } else {
            pythonPath = toPrependStr + pathSep + pythonPath;
        }
        // qputenv on minw will just call putenv, but we want to keep the utf16 info, so we need to call _wputenv
#     if 0//def __NATRON_WIN32__
        _wputenv_s(L"PYTHONPATH", StrUtils::utf8_to_utf16(pythonPath).c_str());
#     else
        ProcInfo::putenv_wrapper( "PYTHONPATH", pythonPath.c_str() );
        //Py_SetPath( pythonPathString.c_str() ); // does not exist in Python 2
#     endif
#     if PY_MAJOR_VERSION >= 3
        std::wstring pythonPathString = StrUtils::utf8_to_utf16(pythonPath);
        Py_SetPath( pythonPathString.c_str() ); // argument is copied internally, no need to use static storage
#     endif
#     if defined(NATRON_CONFIG_SNAPSHOT) || defined(DEBUG)
        printf( "PYTHONPATH set to %s\n", pythonPath.c_str() );
#     endif
    }

} // setupPythonEnv
Esempio n. 24
0
//---------------------------------------------------------------------------------
// Initializes python.
//---------------------------------------------------------------------------------
bool CPythonManager::Initialize( void )
{
	// Construct a path to the python engine directory.
	char szPythonHome[MAX_GAME_PATH];
	V_snprintf(szPythonHome, MAX_GAME_PATH, "%s/Python3", g_GamePaths.GetSPDir());
	V_FixSlashes(szPythonHome);
	DevMsg(1, "[SP] Python home path set to %s\n", szPythonHome);

	// Convert to wide char for python.
	wchar_t wszPythonHome[1024];
	V_strtowcs(szPythonHome, -1, wszPythonHome, 1024);

	// Set that as the python home directory.
 	Py_SetPythonHome(wszPythonHome);
 	Py_SetProgramName(wszPythonHome);
	Py_SetPath(wszPythonHome);

	// Initialize python and its namespaces.
	Py_Initialize();

	// Print some information
	DevMsg(1, "Python version %s initialized!\n", Py_GetVersion());

	// Make sure sys is imported.
	PyRun_SimpleString("import sys");

	// Add the Python API path.
	AddToSysPath("/packages/source-python");

	// Add operating system specific paths.
#if defined(WIN32)
	AddToSysPath("/Python3/plat-win");
#else
	AddToSysPath("/Python3/plat-linux");

	// We've got a bunch of linux shared objects here we need to load.
	AddToSysPath("/Python3/lib-dynload");
#endif

	// Site packages for any extra packages...
	AddToSysPath("/packages/site-packages");

	// Add the custom packages path.
	AddToSysPath("/packages/custom");

	// And of course, the plugins directory for script imports.
	AddToSysPath("/plugins");

	// Initialize all converters
	InitConverters();

	// Initialize all submodules
	modulsp_init();

	// Import the main module file.
	DevMsg(1, "[SP] Importing main module..\n");
	BEGIN_BOOST_PY()

		python::import("__init__");

	END_BOOST_PY_NORET(); // Noret because we have more stuff to do after this import.

	DevMsg(0, "[Source.Python] Loaded successfully.\n");

	return true;
}
Esempio n. 25
0
void PySetup::set_python_home(const std::wstring& python_home)
{
	PySetup::python_home = python_home;
	Py_SetPythonHome(const_cast<wchar_t*>(PySetup::python_home.c_str()));
}
Esempio n. 26
0
void
pbs_python_ext_quick_start_interpreter(void)
{
	static char func_id[] = "pbs_python_ext_quick_start_interpreter";

#ifdef	PYTHON           /* -- BEGIN ONLY IF PYTHON IS CONFIGURED -- */

	char pbs_python_home[MAXPATHLEN+1];
	char pbs_python_destlib[MAXPATHLEN+1];

	memset((char *)pbs_python_home, '\0', MAXPATHLEN+1);
	memset((char *)pbs_python_destlib, '\0', MAXPATHLEN+1);

	snprintf(pbs_python_home, MAXPATHLEN, "%s/python",
		pbs_conf.pbs_exec_path);
	snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib/python/altair",
		pbs_conf.pbs_exec_path);

	Py_NoSiteFlag = 1;
	Py_FrozenFlag = 1;
	Py_OptimizeFlag = 2;            /* TODO make this a compile flag variable */
	Py_IgnoreEnvironmentFlag = 1;   /* ignore PYTHONPATH and PYTHONHOME */
	if (file_exists(pbs_python_home))
		Py_SetPythonHome(pbs_python_home);

	/* we make sure our top level module is initialized */
	if ((PyImport_ExtendInittab(pbs_python_inittab_modules) != 0)) {
		log_err(-1, "PyImport_ExtendInittab",
			"--> Failed to initialize Python interpreter <--");
		return;
	}

	Py_InitializeEx(0);  /* SKIP initialization of signals */

	if (Py_IsInitialized()) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"--> Python Interpreter quick started, compiled with version:'%.*s' <--",
			5, Py_GetVersion());
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
			PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
			LOG_INFO, func_id, log_buffer);
	} else {
		log_err(-1, "Py_InitializeEx",
			"--> Failed to quick initialize Python interpreter <--");
		goto ERROR_EXIT;
	}
	/*
	 * Add Altair python module directory to sys path. NOTE:
	 *  PBS_PYTHON_MODULE_DIR is a command line define, also insert
	 * standard required python modules
	 */
	if (pbs_python_modify_syspath(pbs_python_destlib, -1) == -1) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"could not insert %s into sys.path shutting down",
			pbs_python_destlib);
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_err(-1, func_id, log_buffer);
		goto ERROR_EXIT;
	}

	snprintf(log_buffer, LOG_BUF_SIZE-1,
		"--> Inserted Altair PBS Python modules dir '%s' <--",
		pbs_python_destlib);
	log_buffer[LOG_BUF_SIZE-1] = '\0';
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, func_id, log_buffer);

	return;

ERROR_EXIT:
	pbs_python_ext_quick_shutdown_interpreter();
	return;
#else   /* !PYTHON */
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, "start_python",
		"--> Python interpreter not built in <--");
	return;
#endif  /* PYTHON */

}
Esempio n. 27
0
void
pbs_python_ext_start_interpreter(
	struct python_interpreter_data *interp_data)
{
	static char func_id[] = "pbs_python_ext_start_interpreter";

#ifdef	PYTHON           /* -- BEGIN ONLY IF PYTHON IS CONFIGURED -- */

	struct stat sbuf;
	char pbs_python_home[MAXPATHLEN+1];
	char pbs_python_destlib[MAXPATHLEN+1];
	int  evtype;
	int  rc;

	/*
	 * initialize the convenience global pbs_python_daemon_name, as it is
	 * used everywhere
	 */

	pbs_python_daemon_name = interp_data->daemon_name;

	/* Need to make logging less verbose if pbs_python command */
	/* used, since it can get called many times in a pbs daemon, */
	/* and it would litter that daemon's logs */
	if (IS_PBS_PYTHON_CMD(pbs_python_daemon_name))
		evtype = PBSEVENT_DEBUG3;
	else
		evtype = PBSEVENT_DEBUG2;

	memset((char *)pbs_python_home, '\0', MAXPATHLEN+1);
	memset((char *)pbs_python_destlib, '\0', MAXPATHLEN+1);

	snprintf(pbs_python_home, MAXPATHLEN, "%s/python",
		pbs_conf.pbs_exec_path);
	snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib64/python/altair",
		pbs_conf.pbs_exec_path);
	rc = stat(pbs_python_destlib, &sbuf);
	if (rc != 0) {
		snprintf(pbs_python_destlib, MAXPATHLEN, "%s/lib/python/altair",
			pbs_conf.pbs_exec_path);
		rc = stat(pbs_python_destlib, &sbuf);
	}
	if (rc != 0) {
		log_err(-1, func_id,
			"--> PBS Python library directory not found <--");
		return;
	}
	if (!S_ISDIR(sbuf.st_mode)) {
		log_err(-1, func_id,
			"--> PBS Python library path is not a directory <--");
		return;
	}

	if (interp_data) {
		interp_data->init_interpreter_data(interp_data); /* to be safe */
		if (interp_data->interp_started) {
			log_event(evtype, PBS_EVENTCLASS_SERVER,
				LOG_INFO, interp_data->daemon_name,
				"--> Python interpreter already started <--");
			return;
		}
	} else { /* we need to allocate memory */
		log_err(-1, func_id,
			"--> Passed NULL for interpreter data <--");
		return;
	}

	Py_NoSiteFlag = 1;
	Py_FrozenFlag = 1;
	Py_OptimizeFlag = 2;            /* TODO make this a compile flag variable */
	Py_IgnoreEnvironmentFlag = 1;   /* ignore PYTHONPATH and PYTHONHOME */
	if (file_exists(pbs_python_home))
		Py_SetPythonHome(pbs_python_home);

	/* we make sure our top level module is initialized */
	if ((PyImport_ExtendInittab(pbs_python_inittab_modules) != 0)) {
		log_err(-1, "PyImport_ExtendInittab",
			"--> Failed to initialize Python interpreter <--");
		return;
	}


	Py_InitializeEx(1);  /* arg '1' means to not skip init of signals -    */
	/* we want signals to propagate to the executing  */
	/* Python script to be able to interrupt it       */

	if (Py_IsInitialized()) {
		interp_data->interp_started = 1; /* mark python as initialized */
		/* print only the first five characters, TODO check for NULL? */
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"--> Python Interpreter started, compiled with version:'%.*s' <--",
			5, Py_GetVersion());
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_event(evtype, PBS_EVENTCLASS_SERVER,
			LOG_INFO, interp_data->daemon_name, log_buffer);
	} else {
		log_err(-1, "Py_InitializeEx",
			"--> Failed to initialize Python interpreter <--");
		goto ERROR_EXIT;
	}
	/*
	 * Add Altair python module directory to sys path. NOTE:
	 *  PBS_PYTHON_MODULE_DIR is a command line define, also insert
	 * standard required python modules
	 */
	if (pbs_python_modify_syspath(pbs_python_destlib, -1) == -1) {
		snprintf(log_buffer, LOG_BUF_SIZE-1,
			"could not insert %s into sys.path shutting down",
			pbs_python_destlib);
		log_buffer[LOG_BUF_SIZE-1] = '\0';
		log_err(-1, func_id, log_buffer);
		goto ERROR_EXIT;
	}

	/*
	 * At this point it is safe to load the available server types from
	 * the python modules. since the syspath is setup correctly
	 */
	if ((pbs_python_load_python_types(interp_data) == -1)) {
		log_err(-1, func_id, "could not load python types into the interpreter");
		goto ERROR_EXIT;
	}

	interp_data->pbs_python_types_loaded = 1; /* just in case */
	return;

ERROR_EXIT:
	pbs_python_ext_shutdown_interpreter(interp_data);
	return;
#else  /* !PYTHON */
	log_event(PBSEVENT_SYSTEM|PBSEVENT_ADMIN |
		PBSEVENT_DEBUG, PBS_EVENTCLASS_SERVER,
		LOG_INFO, "start_python",
		"--> Python interpreter not built in <--");
	return;
#endif /* PYTHON */
}
Esempio n. 28
0
void initialize_interpreter(int argc, char **argv, char *outr, char *errr,
        const char *basename, const char *module, const char *function) {
    char *path, *encoding, *p;

    get_paths();

    path = (char*)calloc(3*PATH_MAX, sizeof(char));
    if (!path) OOM;

    snprintf(path, 3*PATH_MAX,
            "%s/%s:%s/%s/plat-linux2:%s/%s/lib-dynload:%s/%s/site-packages",
            lib_dir, PYTHON_VER, lib_dir, PYTHON_VER, lib_dir, PYTHON_VER,
            lib_dir, PYTHON_VER);

    Py_OptimizeFlag = 2;
    Py_NoSiteFlag = 1;
    Py_DontWriteBytecodeFlag = 1;
    Py_IgnoreEnvironmentFlag = 1;
    Py_NoUserSiteDirectory = 1;
    Py_VerboseFlag = 0;
    Py_DebugFlag = 0;

    Py_SetProgramName(exe_path);
    Py_SetPythonHome(base_dir);

    //printf("Path before Py_Initialize(): %s\r\n\n", Py_GetPath()); 
    Py_Initialize();
    if (!Py_FileSystemDefaultEncoding) {
        encoding = getenv("PYTHONIOENCODING");
        if (encoding != NULL) {
            Py_FileSystemDefaultEncoding = strndup(encoding, 20);
            p = index(Py_FileSystemDefaultEncoding, ':');
            if (p != NULL) *p = 0;
        } else
            Py_FileSystemDefaultEncoding = strndup("UTF-8", 10);
    }


    setup_streams();

    PySys_SetArgv(argc, argv);
    //printf("Path after Py_Initialize(): %s\r\n\n", Py_GetPath());
    PySys_SetPath(path);
    //printf("Path set by me: %s\r\n\n", path);
    PySys_SetObject("gui_app", PyBool_FromLong((long)GUI_APP));
    PySys_SetObject("calibre_basename", PyBytes_FromString(basename));
    PySys_SetObject("calibre_module",   PyBytes_FromString(module));
    PySys_SetObject("calibre_function", PyBytes_FromString(function));
    PySys_SetObject("extensions_location", PyBytes_FromString(extensions_dir));
    PySys_SetObject("resources_location", PyBytes_FromString(resources_dir));
    PySys_SetObject("executables_location", PyBytes_FromString(base_dir));
    PySys_SetObject("frozen_path", PyBytes_FromString(base_dir));
    PySys_SetObject("frozen", Py_True);
    Py_INCREF(Py_True);


    if (GUI_APP && outr && errr) {
    //    PySys_SetObject("stdout_redirect", PyUnicode_FromWideChar(outr, wcslen(outr)));
    //    PySys_SetObject("stderr_redirect", PyUnicode_FromWideChar(errr, wcslen(outr)));
    }

}
Esempio n. 29
0
int uwsgi_python_init() {

#ifndef UWSGI_PYPY
	char *pyversion = strchr(Py_GetVersion(), '\n');
	if (!pyversion) {
        	uwsgi_log_initial("Python version: %s\n", Py_GetVersion());
	}
	else {
        	uwsgi_log_initial("Python version: %.*s %s\n", pyversion-Py_GetVersion(), Py_GetVersion(), Py_GetCompiler()+1);
	}
#else
	uwsgi_log_initial("PyPy version: %s\n", PYPY_VERSION);
#endif

	if (up.home != NULL) {
#ifdef PYTHREE
		wchar_t *wpyhome;
		wpyhome = malloc((sizeof(wchar_t) * strlen(up.home)) + sizeof(wchar_t) );
		if (!wpyhome) {
			uwsgi_error("malloc()");
			exit(1);
		}
		mbstowcs(wpyhome, up.home, strlen(up.home));
		Py_SetPythonHome(wpyhome);
		// do not free this memory !!!
		//free(wpyhome);
#else
		Py_SetPythonHome(up.home);
#endif
		uwsgi_log("Set PythonHome to %s\n", up.home);
	}


#ifdef PYTHREE
	wchar_t pname[6];
	mbstowcs(pname, "uWSGI", 6);
	Py_SetProgramName(pname);
#else
	Py_SetProgramName("uWSGI");
#endif


#ifndef UWSGI_PYPY
	Py_OptimizeFlag = up.optimize;
#endif

	Py_Initialize();

	if (!uwsgi.has_threads) {
		uwsgi_log("*** Python threads support is disabled. You can enable it with --enable-threads ***\n");
	}

	up.wsgi_spitout = PyCFunction_New(uwsgi_spit_method, NULL);
	up.wsgi_writeout = PyCFunction_New(uwsgi_write_method, NULL);

	up.main_thread = PyThreadState_Get();

        // by default set a fake GIL (little impact on performance)
        up.gil_get = gil_fake_get;
        up.gil_release = gil_fake_release;

        up.swap_ts = simple_swap_ts;
        up.reset_ts = simple_reset_ts;
	

	uwsgi_log_initial("Python main interpreter initialized at %p\n", up.main_thread);

	return 1;

}
Esempio n. 30
0
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";
    }
  }
}