Exemple #1
0
static int mod_init(rlm_python_t *inst)
{
	int i;
	static char name[] = "radiusd";

	if (radiusd_module) return 0;

	/*
	 *	Explicitly load libpython, so symbols will be available to lib-dynload modules
	 */
	inst->libpython = dlopen("libpython" STRINGIFY(PY_MAJOR_VERSION) "." STRINGIFY(PY_MINOR_VERSION) ".so",
				 RTLD_NOW | RTLD_GLOBAL);
	if (!inst->libpython) {
	 	WARN("Failed loading libpython symbols into global symbol table: %s", dlerror());
	}

	Py_SetProgramName(name);
#ifdef HAVE_PTHREAD_H
	Py_InitializeEx(0);				/* Don't override signal handlers */
	PyEval_InitThreads(); 				/* This also grabs a lock */
	inst->main_thread_state = PyThreadState_Get();	/* We need this for setting up thread local stuff */
#endif
	if (inst->python_path) {
		PySys_SetPath(inst->python_path);
	}

	if ((radiusd_module = Py_InitModule3("radiusd", radiusd_methods,
					     "FreeRADIUS Module.")) == NULL)
		goto failed;

	for (i = 0; radiusd_constants[i].name; i++) {
		if ((PyModule_AddIntConstant(radiusd_module, radiusd_constants[i].name,
					     radiusd_constants[i].value)) < 0) {
			goto failed;
		}
	}

#ifdef HAVE_PTHREAD_H
	PyThreadState_Swap(NULL);	/* We have to swap out the current thread else we get deadlocks */
	PyEval_ReleaseLock();		/* Drop lock grabbed by InitThreads */
#endif
	DEBUG("mod_init done");
	return 0;

failed:
	Py_XDECREF(radiusd_module);

#ifdef HAVE_PTHREAD_H
	PyEval_ReleaseLock();
#endif

	Pyx_BLOCK_THREADS
	mod_error();
	Pyx_UNBLOCK_THREADS

	radiusd_module = NULL;

	Py_Finalize();
	return -1;
}
Exemple #2
0
PythonLoader::PythonLoader(QObject *parent) : QObject(parent)
{

    if (!Py_IsInitialized())
    {
        QString sysPath = QCoreApplication::applicationDirPath();
        QString programPath = sysPath + "/thirdparty/Python/bin/python3";
        wchar_t* programName = new wchar_t[programPath.length() + 1];
        programPath.toWCharArray(programName);
        programName[programPath.length()] = 0;

        Py_SetProgramName(programName);
        wprintf(L"python prefix path: %S\n", Py_GetPrefix());
        wprintf(L"python full path: %S\n", Py_GetProgramFullPath());
        Py_Initialize();
        QStringList paths = {sysPath+"/thirdparty/Python/lib/python3.4", sysPath+"/thirdparty/Python/lib/python3.4/plat-linux",
                             sysPath+"/thirdparty/Python/lib/python3.4/lib-dynload", sysPath+"/thirdparty/Python/lib/python3.4/site-packages",
                            sysPath, sysPath+"/thirdparty/Python/lib", sysPath+"/thirdparty/Python/bin"};
        QString wholePath = paths.join(":");
        PySys_SetPath(wholePath.toStdWString().c_str());

        getSipAPI();
        PyEval_InitThreads();
        PyEval_SaveThread();
    }
}
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;
}
Exemple #4
0
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);

}
Exemple #5
0
	void PythonEngine::init()
	{
		Engine::out(Engine::ERROR) << "[PyScript] init:" << std::endl;
		//Py_SetProgramName(argv[0]);
		Py_Initialize();

		PySys_SetPath( L".:res/scripting:/usr/lib64/python3.3" );
		PyObject *module = PyImport_Import(PyUnicode_FromString("SBE"));

		RunFile("res/scripting/__init__.py");
		Engine::out(Engine::ERROR) << "[PyScript] initialized." << std::endl;
	}
Exemple #6
0
/**
 * Add an additional search directory for the protocol decoders.
 *
 * The specified directory is prepended (not appended!) to Python's sys.path,
 * in order to search for sigrok protocol decoders in the specified
 * directories first, and in the generic Python module directories (and in
 * the current working directory) last. This avoids conflicts if there are
 * Python modules which have the same name as a sigrok protocol decoder in
 * sys.path or in the current working directory.
 *
 * @param path Path to the directory containing protocol decoders which shall
 *             be added to the Python sys.path, or NULL.
 *
 * @return SRD_OK upon success, a (negative) error code otherwise.
 */
SRD_PRIV int srd_decoder_searchpath_add(const char *path)
{
	PyObject *py_cur_path, *py_item;
	GString *new_path;
	int wc_len, i;
	wchar_t *wc_new_path;
	char *item;

	srd_dbg("Adding '%s' to module path.", path);

	new_path = g_string_sized_new(256);
	g_string_assign(new_path, g_strdup(path));
	py_cur_path = PySys_GetObject("path");
	for (i = 0; i < PyList_Size(py_cur_path); i++) {
		g_string_append(new_path, g_strdup(G_SEARCHPATH_SEPARATOR_S));
		py_item = PyList_GetItem(py_cur_path, i);
		if (!PyUnicode_Check(py_item))
			/* Shouldn't happen. */
			continue;
		if (py_str_as_str(py_item, &item) != SRD_OK)
			continue;
		g_string_append(new_path, item);
	}

	/* Convert to wide chars. */
	wc_len = sizeof(wchar_t) * (new_path->len + 1);
	if (!(wc_new_path = g_try_malloc(wc_len))) {
		srd_dbg("malloc failed");
		return SRD_ERR_MALLOC;
	}
	mbstowcs(wc_new_path, new_path->str, wc_len);
	PySys_SetPath(wc_new_path);
	g_string_free(new_path, TRUE);
	g_free(wc_new_path);

//#ifdef _WIN32
//	gchar **splitted;
//
//	/*
//	 * On Windows/MinGW, Python's sys.path needs entries of the form
//	 * 'C:\\foo\\bar' instead of '/foo/bar'.
//	 */
//
//	splitted = g_strsplit(DECODERS_DIR, "/", 0);
//	path = g_build_pathv("\\\\", splitted);
//	g_strfreev(splitted);
//#else
//	path = g_strdup(DECODERS_DIR);
//#endif

	return SRD_OK;
}
static int mod_init(rlm_python_t *inst)
{
	int i;
	static char name[] = "radiusd";

	if (radiusd_module) return 0;

	Py_SetProgramName(name);
#ifdef HAVE_PTHREAD_H
	Py_InitializeEx(0);				/* Don't override signal handlers */
	PyEval_InitThreads(); 				/* This also grabs a lock */
	inst->main_thread_state = PyThreadState_Get();	/* We need this for setting up thread local stuff */
#endif
	if (inst->python_path) {
		PySys_SetPath(inst->python_path);
	}
	
	if ((radiusd_module = Py_InitModule3("radiusd", radiusd_methods,
					     "FreeRADIUS Module.")) == NULL)
		goto failed;

	for (i = 0; radiusd_constants[i].name; i++) {
		if ((PyModule_AddIntConstant(radiusd_module, radiusd_constants[i].name,
					     radiusd_constants[i].value)) < 0) {
			goto failed;
		}
	}

#ifdef HAVE_PTHREAD_H
	PyThreadState_Swap(NULL);	/* We have to swap out the current thread else we get deadlocks */
	PyEval_ReleaseLock();		/* Drop lock grabbed by InitThreads */
#endif
	DEBUG("mod_init done");
	return 0;

failed:
	Py_XDECREF(radiusd_module);

#ifdef HAVE_PTHREAD_H
	PyEval_ReleaseLock();
#endif

	Pyx_BLOCK_THREADS
	mod_error();
	Pyx_UNBLOCK_THREADS

	radiusd_module = NULL;

	Py_Finalize();
	return -1;
}
Exemple #8
0
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());
	}
Exemple #10
0
int main(int argc, char *argv[])
{
    setenv("PYTHONHOME", PYTHON_HOME, 1);
    setenv("PYTHONPATH", PYTHON_PATH, 1);
    setenv("LD_LIBRARY_PATH", LD_LIBRARY_PATH, 1);
    setenv("PATH", PATH, 1);

    QApplication app(argc, argv);
    Py_Initialize();
    PySys_SetArgv(argc, argv);
    PySys_SetPath(PYTHON_PATH);
    FILE *fp = fopen(PYQT_MAIN, "r");
    PyRun_SimpleFile(fp, PYQT_MAIN);
    fclose(fp);
    Py_Finalize();
    //app.exec();
}
Exemple #11
0
int main_thread(SceSize args, void *argp)
{
    FILE *fp;
    int argc = 1;
    char *argv[] = {save_argv0};

#ifdef WITH_PSP2D
    sceGuInit();
#endif

    Py_Initialize();

    PySys_SetPath("ms0:/python");
    PySys_SetArgv(argc, argv);

    fp = fopen("script.py", "r");
    if (fp)
    {
       PyRun_SimpleFile(fp, "script.py");
       fclose(fp);
    }
    else
    {
#ifndef DEBUG
       pspDebugScreenInit();
#endif

       pspDebugScreenPrintf("Error - could not open script.py\n");
    }

#ifdef DEBUG
    sceKernelDelayThreadCB(1e7);
#endif

    Py_Finalize();

#ifdef WITH_PSP2D
    sceGuTerm();
#endif

    sceKernelExitGame();

    return 0;
}
Exemple #12
0
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);
}
Exemple #13
0
//## PyObject PyObject.importPtModule(String name);
//[TODO] devide each function PYTHONPATH and default search path.
static KMETHOD PyObject_import(KonohaContext *kctx, KonohaStack *sfp)
{
	PySys_SetPath("."); // add home dir to python search path.
	PyListObject* ppath;
	ppath = (PyListObject*)PyList_New(0);
	PyList_Append((PyObject*)ppath, PyString_FromString("."));
	// add home dir to python search path.
	const char *path = PLATAPI getenv_i("PYTHONPATH");
	if (path != NULL) {
		size_t i;
		char** pathes = pyenv_split((char *)path, ':');
		for (i = 0; pathes[i] != NULL; i++) {
			PyList_Append((PyObject*)ppath, PyString_FromString(pathes[i]));
			free(pathes[i]);
		}
		free(pathes);
	}
	PySys_SetObject("path", (PyObject*)ppath);
	RETURN_PyObject(PyImport_ImportModule(S_text(sfp[1].asString)));
}
int main(int, char*[])
{
  OneClass *oc = new OneClass(2);
  oc->set("the current value is");
  std::cout << oc->calc() << std::endl;

  Py_Initialize();
  PySys_SetPath(L"."); 
  
  PyObject *pName = PyUnicode_FromString("doit");
  assert(pName!=0);
  PyObject *pModule = PyImport_Import(pName);
  assert(pModule!=0);
  Py_DECREF(pName);

  initOneClass(pModule);

  PyObject *pFunc = PyObject_GetAttrString(pModule, "f");

  PyObject *pArgs = PyTuple_New(2);

  PyObject *ocValue = createOneClass(pModule,oc);
  assert(((pyOneClass*)ocValue)->oneclass->getNumber() == 2);
  //PyObject *pValue = PyLong_FromLong(1);
  PyTuple_SetItem(pArgs,0,ocValue);

  PyObject* pValue = PyLong_FromLong(3);
  PyTuple_SetItem(pArgs,1,pValue);

  PyObject_CallObject(pFunc, pArgs);
  
  Py_DECREF(pFunc);
  Py_DECREF(pModule);

  std::cout << oc->calc() << std::endl;

  Py_DECREF(pArgs);

  return 0;
}
Exemple #15
0
/**
 * Add an additional search directory for the protocol decoders.
 *
 * The specified directory is prepended (not appended!) to Python's sys.path,
 * in order to search for sigrok protocol decoders in the specified
 * directories first, and in the generic Python module directories (and in
 * the current working directory) last. This avoids conflicts if there are
 * Python modules which have the same name as a sigrok protocol decoder in
 * sys.path or in the current working directory.
 *
 * @param path Path to the directory containing protocol decoders which shall
 *             be added to the Python sys.path, or NULL.
 *
 * @return SRD_OK upon success, a (negative) error code otherwise.
 *
 * @private
 *
 * @since 0.1.0
 */
SRD_PRIV int srd_decoder_searchpath_add(const char *path)
{
	PyObject *py_cur_path, *py_item;
	GString *new_path;
	int wc_len, i;
	wchar_t *wc_new_path;
	char *item;

	srd_dbg("Adding '%s' to module path.", path);

	new_path = g_string_sized_new(256);
	g_string_assign(new_path, path);
	py_cur_path = PySys_GetObject("path");
	for (i = 0; i < PyList_Size(py_cur_path); i++) {
		g_string_append(new_path, G_SEARCHPATH_SEPARATOR_S);
		py_item = PyList_GetItem(py_cur_path, i);
		if (!PyUnicode_Check(py_item))
			/* Shouldn't happen. */
			continue;
		if (py_str_as_str(py_item, &item) != SRD_OK)
			continue;
		g_string_append(new_path, item);
		g_free(item);
	}

	/* Convert to wide chars. */
	wc_len = sizeof(wchar_t) * (new_path->len + 1);
	if (!(wc_new_path = g_try_malloc(wc_len))) {
		srd_dbg("malloc failed");
		return SRD_ERR_MALLOC;
	}
	mbstowcs(wc_new_path, new_path->str, wc_len);
	PySys_SetPath(wc_new_path);
	g_string_free(new_path, TRUE);
	g_free(wc_new_path);

	return SRD_OK;
}
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
}
Exemple #17
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");
}
Exemple #18
0
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);

*/
}
Exemple #19
0
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();
}
Exemple #20
0
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 */
}
Exemple #21
0
uint32_t mainThread(int argc, char *argv[], bool so) {

	int rc = 0;
	PyObject *m=NULL, *d=NULL, *seq=NULL;
	PyObject *mod;
	char * ppath;
	FILE * f;
	uintptr_t cookie = 0;
	PyGILState_STATE restore_state;

	if(!Py_IsInitialized) {
		int res=0;

		if(!_load_python(
				"libpython2.7.so",
				resources_python27_so_start,
				resources_python27_so_size)) {
			dprint("loading libpython2.7.so from memory failed\n");
			return -1;
		}
	}

	dprint("calling PyEval_InitThreads() ...\n");
	PyEval_InitThreads();
	dprint("PyEval_InitThreads() called\n");

	if(!Py_IsInitialized()) {
		dprint("Py_IsInitialized\n");

		Py_IgnoreEnvironmentFlag = 1;
		Py_NoSiteFlag = 1; /* remove site.py auto import */

		dprint("INVOCATION NAME: %s\n", program_invocation_name);
		Py_SetProgramName(program_invocation_name);

		dprint("Initializing python.. (%p)\n", Py_Initialize);
		Py_InitializeEx(0);

		dprint("SET ARGV\n");
		if (argc > 0) {
			if (so) {
				if (argc > 2 && !strcmp(argv[1], "--pass-args")) {
					argv[1] = argv[0];
					PySys_SetArgvEx(argc - 1, argv + 1, 0);
				} else {
					PySys_SetArgvEx(1, argv, 0);
				}
			} else {
				PySys_SetArgvEx(argc, argv, 0);
			}
		}

		PySys_SetPath(".");
#ifndef DEBUG
		PySys_SetObject("frozen", PyBool_FromLong(1));
#endif

		dprint("Py_Initialize() complete\n");
	}
	restore_state=PyGILState_Ensure();

	init_memimporter();
	dprint("init_memimporter()\n");
	initpupy();
	dprint("initpupy()\n");

#ifdef _PYZLIB_DYNLOAD
	dprint("load zlib\n");
    if (!import_module("initzlib", "zlib", resources_zlib_so_start, resources_zlib_so_size)) {
        dprint("ZLib load failed.\n");
    }
#endif

	/* We execute then in the context of '__main__' */
	dprint("starting evaluating python code ...\n");
	m = PyImport_AddModule("__main__");
	if (m) d = PyModule_GetDict(m);
	if (d) seq = PyMarshal_ReadObjectFromString(
		resources_bootloader_pyc_start,
		resources_bootloader_pyc_size
	);

	if (seq) {
		Py_ssize_t i, max = PySequence_Length(seq);
		for (i=0;i<max;i++) {
			dprint("LOAD SEQUENCE %d\n", i);
			PyObject *sub = PySequence_GetItem(seq, i);
			if (seq) {
				PyObject *discard = PyEval_EvalCode((PyCodeObject *)sub, d, d);
				if (!discard) {
					dprint("discard\n");
					PyErr_Print();
					rc = 255;
				}
				Py_XDECREF(discard);
				/* keep going even if we fail */
			}
			Py_XDECREF(sub);
		}
	}
	dprint("complete ...\n");
	PyGILState_Release(restore_state);
	Py_Finalize();
	dprint("exit ...\n");
	return 0;
}
Exemple #22
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)));
    }

}
Exemple #23
0
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();
}
Exemple #24
0
int runtime (int argc, char * argv[])
{
  QApplication app(argc, argv);

  qmlRegisterType <RFGisQMLMap> ("RFGis", 1, 0, "Map");


#if !defined (ANDROID)  
  setenv ("AUTOCONF_PROJECT_CODE_PATH", PROJECT_CODE_PATH, 1);
#else
  char *android_argv[3];
  android_argv[0] = argv[0];

  QString prefix_path = "--prefix-path=" % QString(getenv("PREFIX_PATH"));
  QString plugin_path = "--plugin-path=" % QString(getenv("PLUGIN_PATH"));
  QString app_path = QString(getenv("PREFIX_PATH")) % "/files/application";

  qDebug() << "Prefix Path: " << prefix_path;
  qDebug() << "Plugin Path: " << plugin_path;
  qDebug() << "Application: " << app_path;

  char *alloca_prefix = new char[prefix_path.size () + 1];
  char *alloca_plugin = new char[plugin_path.size () + 1];
  char *alloca_app = new char[app_path.size () + 1];

  memset (alloca_prefix, 0, prefix_path.size () + 1);
  memset (alloca_plugin, 0, plugin_path.size () + 1);
  memset (alloca_app, 0, app_path.size () + 1);

  QByteArray prefix_ba = prefix_path.toUtf8();
  QByteArray plugin_ba = plugin_path.toUtf8();
  QByteArray app_ba = app_path.toUtf8();

  memcpy(alloca_prefix, prefix_ba.constData (), prefix_path.size ());
  memcpy(alloca_plugin, plugin_ba.constData (), plugin_path.size ());
  memcpy(alloca_app, app_ba.constData (), app_path.size ());

  qDebug() << "Allocated Prefix" << QString(alloca_prefix);
  qDebug() << "Allocated Plugin" << QString(alloca_plugin);
  qDebug() << "Allocated Application" << QString(alloca_app);

  android_argv[1] = alloca_prefix;
  android_argv[2] = alloca_plugin;
  
  setenv ("AUTOCONF_PROJECT_CODE_PATH", alloca_app, 1);
#endif

  Py_Initialize();

#if !defined (ANDROID)
  PySys_SetArgv(argc, argv);
#else
  PySys_SetArgv(3, android_argv);  
#endif

  QString python_path = QString(getenv("PYTHONPATH"));
  
#if defined (HAVE_GETPID) && !defined (ANDROID) && HAVE_GETPID == 1
  if (python_path.size ())
    {
      python_path += ":" + getBasePath();
    }
  else
    {
      python_path = getBasePath();
    }
#endif

  if (python_path.size ()) python_path += ":";
  python_path += ".";

  char *python_path_buffer = 0;
  char path_object_name[5];

  qDebug() << "Additional python path: " << python_path;
  memcpy(path_object_name, "path", 5);

  PyObject *sys_path = PySys_GetObject(path_object_name);
  if (sys_path != 0)
    {
      QStringList paths_list = python_path.split(':');
      for (int i = 0; i < paths_list.size(); ++i)
	{
	  char *buffer = 0;
	  QByteArray b_path = paths_list[i].toLatin1();
	  const char *path = b_path.data();
	  size_t len = strlen(path) + 1;
	  buffer = new char[len];
	  memcpy(buffer, path, len);
	  PyList_Append(sys_path, PyString_FromString(buffer));
	  delete buffer;
	}
    }
  else
    {
      QByteArray b_path = python_path.toLatin1();
      const char *path = b_path.data();
      size_t len = strlen(path) + 1;
      python_path_buffer = new char[len];
      memcpy(python_path_buffer, path, len);
      PySys_SetPath(python_path_buffer);
    }

  PyEval_InitThreads();

  preConfigure ();

  qDebug() << "Preconfiguration Finished";

  RFGisConfigure config;
  
  RFGisInitialization (config.prefix_path (), config.plugin_path ());

  configure ();

#if defined (ANDROID)
  run_interactivenetconsole ();
#endif
  int code = app.exec ();
  rfgisExit(code);
  return code;
}
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 */
}
Exemple #26
0
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;
}
Exemple #27
0
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());
}
Exemple #28
0
/* int main(int argc, char **argv) { */
int main(int argc, char *argv[]) {

  char *env_argument = NULL;
  char *env_entrypoint = NULL;
  char *env_logname = NULL;
  char entrypoint[ENTRYPOINT_MAXLEN];
  int ret = 0;
  FILE *fd;

  LOGP("Initializing Python for Android");

  // Set a couple of built-in environment vars:
  setenv("P4A_BOOTSTRAP", bootstrap_name, 1);  // env var to identify p4a to applications
  env_argument = getenv("ANDROID_ARGUMENT");
  setenv("ANDROID_APP_PATH", env_argument, 1);
  env_entrypoint = getenv("ANDROID_ENTRYPOINT");
  env_logname = getenv("PYTHON_NAME");
  if (!getenv("ANDROID_UNPACK")) {
    /* ANDROID_UNPACK currently isn't set in services */
    setenv("ANDROID_UNPACK", env_argument, 1);
  }
  if (env_logname == NULL) {
    env_logname = "python";
    setenv("PYTHON_NAME", "python", 1);
  }

  // Set additional file-provided environment vars:
  LOGP("Setting additional env vars from p4a_env_vars.txt");
  char env_file_path[256];
  snprintf(env_file_path, sizeof(env_file_path),
           "%s/p4a_env_vars.txt", getenv("ANDROID_UNPACK"));
  FILE *env_file_fd = fopen(env_file_path, "r");
  if (env_file_fd) {
    char* line = NULL;
    size_t len = 0;
    while (getline(&line, &len, env_file_fd) != -1) {
      if (strlen(line) > 0) {
        char *eqsubstr = strstr(line, "=");
        if (eqsubstr) {
          size_t eq_pos = eqsubstr - line;

          // Extract name:
          char env_name[256];
          strncpy(env_name, line, sizeof(env_name));
          env_name[eq_pos] = '\0';

          // Extract value (with line break removed:
          char env_value[256];
          strncpy(env_value, (char*)(line + eq_pos + 1), sizeof(env_value));
          if (strlen(env_value) > 0 &&
              env_value[strlen(env_value)-1] == '\n') {
            env_value[strlen(env_value)-1] = '\0';
            if (strlen(env_value) > 0 &&
                env_value[strlen(env_value)-1] == '\r') {
              // Also remove windows line breaks (\r\n)
              env_value[strlen(env_value)-1] = '\0';
            } 
          }

          // Set value:
          setenv(env_name, env_value, 1);
        }
      }
    }
    fclose(env_file_fd);
  } else {
    LOGP("Warning: no p4a_env_vars.txt found / failed to open!");
  }

  LOGP("Changing directory to the one provided by ANDROID_ARGUMENT");
  LOGP(env_argument);
  chdir(env_argument);

#if PY_MAJOR_VERSION < 3
  Py_NoSiteFlag=1;
#endif

#if PY_MAJOR_VERSION < 3
  Py_SetProgramName("android_python");
#else
  Py_SetProgramName(L"android_python");
#endif

#if PY_MAJOR_VERSION >= 3
  /* our logging module for android
   */
  PyImport_AppendInittab("androidembed", initandroidembed);
#endif

  LOGP("Preparing to initialize python");

  // Set up the python path
  char paths[256];

  char crystax_python_dir[256];
  snprintf(crystax_python_dir, 256,
           "%s/crystax_python", getenv("ANDROID_UNPACK"));
  char python_bundle_dir[256];
  snprintf(python_bundle_dir, 256,
           "%s/_python_bundle", getenv("ANDROID_UNPACK"));
  if (dir_exists(crystax_python_dir) || dir_exists(python_bundle_dir)) {
    if (dir_exists(crystax_python_dir)) {
        LOGP("crystax_python exists");
        snprintf(paths, 256,
                "%s/stdlib.zip:%s/modules",
                crystax_python_dir, crystax_python_dir);
    }

    if (dir_exists(python_bundle_dir)) {
        LOGP("_python_bundle dir exists");
        snprintf(paths, 256,
                "%s/stdlib.zip:%s/modules",
                python_bundle_dir, python_bundle_dir);
    }

    LOGP("calculated paths to be...");
    LOGP(paths);

    #if PY_MAJOR_VERSION >= 3
        wchar_t *wchar_paths = Py_DecodeLocale(paths, NULL);
        Py_SetPath(wchar_paths);
    #endif

        LOGP("set wchar paths...");
  } else {
      // We do not expect to see crystax_python any more, so no point
      // reminding the user about it. If it does exist, we'll have
      // logged it earlier.
      LOGP("_python_bundle does not exist");
  }

  Py_Initialize();

#if PY_MAJOR_VERSION < 3
  // Can't Py_SetPath in python2 but we can set PySys_SetPath, which must
  // be applied after Py_Initialize rather than before like Py_SetPath
  #if PY_MICRO_VERSION >= 15
    // Only for python native-build
    PySys_SetPath(paths);
  #endif
  PySys_SetArgv(argc, argv);
#endif

  LOGP("Initialized python");

  /* ensure threads will work.
   */
  LOGP("AND: Init threads");
  PyEval_InitThreads();

#if PY_MAJOR_VERSION < 3
  initandroidembed();
#endif

  PyRun_SimpleString("import androidembed\nandroidembed.log('testing python "
                     "print redirection')");

  /* inject our bootstrap code to redirect python stdin/stdout
   * replace sys.path with our path
   */
  PyRun_SimpleString("import sys, posix\n");
  if (dir_exists("lib")) {
    /* If we built our own python, set up the paths correctly.
     * This is only the case if we are using the python2legacy recipe
     */
    LOGP("Setting up python from ANDROID_APP_PATH");
    PyRun_SimpleString("private = posix.environ['ANDROID_APP_PATH']\n"
                       "argument = posix.environ['ANDROID_ARGUMENT']\n"
                       "sys.path[:] = [ \n"
                       "    private + '/lib/python27.zip', \n"
                       "    private + '/lib/python2.7/', \n"
                       "    private + '/lib/python2.7/lib-dynload/', \n"
                       "    private + '/lib/python2.7/site-packages/', \n"
                       "    argument ]\n");
  }

  char add_site_packages_dir[256];
  if (dir_exists(crystax_python_dir)) {
    snprintf(add_site_packages_dir, 256,
             "sys.path.append('%s/site-packages')",
             crystax_python_dir);

    PyRun_SimpleString("import sys\n"
                       "sys.argv = ['notaninterpreterreally']\n"
                       "from os.path import realpath, join, dirname");
    PyRun_SimpleString(add_site_packages_dir);
    /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */
    PyRun_SimpleString("sys.path = ['.'] + sys.path");
  }

  if (dir_exists(python_bundle_dir)) {
    snprintf(add_site_packages_dir, 256,
             "sys.path.append('%s/site-packages')",
             python_bundle_dir);

    PyRun_SimpleString("import sys\n"
                       "sys.argv = ['notaninterpreterreally']\n"
                       "from os.path import realpath, join, dirname");
    PyRun_SimpleString(add_site_packages_dir);
    /* "sys.path.append(join(dirname(realpath(__file__)), 'site-packages'))") */
    PyRun_SimpleString("sys.path = ['.'] + sys.path");
  }

  PyRun_SimpleString(
      "class LogFile(object):\n"
      "    def __init__(self):\n"
      "        self.buffer = ''\n"
      "    def write(self, s):\n"
      "        s = self.buffer + s\n"
      "        lines = s.split(\"\\n\")\n"
      "        for l in lines[:-1]:\n"
      "            androidembed.log(l)\n"
      "        self.buffer = lines[-1]\n"
      "    def flush(self):\n"
      "        return\n"
      "sys.stdout = sys.stderr = LogFile()\n"
      "print('Android path', sys.path)\n"
      "import os\n"
      "print('os.environ is', os.environ)\n"
      "print('Android kivy bootstrap done. __name__ is', __name__)");

#if PY_MAJOR_VERSION < 3
  PyRun_SimpleString("import site; print site.getsitepackages()\n");
#endif

  LOGP("AND: Ran string");

  /* run it !
   */
  LOGP("Run user program, change dir and execute entrypoint");

  /* Get the entrypoint, search the .pyo then .py
   */
  char *dot = strrchr(env_entrypoint, '.');
#if PY_MAJOR_VERSION > 2
  char *ext = ".pyc";
#else
  char *ext = ".pyo";
#endif
  if (dot <= 0) {
    LOGP("Invalid entrypoint, abort.");
    return -1;
  }
  if (strlen(env_entrypoint) > ENTRYPOINT_MAXLEN - 2) {
      LOGP("Entrypoint path is too long, try increasing ENTRYPOINT_MAXLEN.");
      return -1;
  }
  if (!strcmp(dot, ext)) {
    if (!file_exists(env_entrypoint)) {
      /* fallback on .py */
      strcpy(entrypoint, env_entrypoint);
      entrypoint[strlen(env_entrypoint) - 1] = '\0';
      LOGP(entrypoint);
      if (!file_exists(entrypoint)) {
        LOGP("Entrypoint not found (.pyc/.pyo, fallback on .py), abort");
        return -1;
      }
    } else {
      strcpy(entrypoint, env_entrypoint);
    }
  } else if (!strcmp(dot, ".py")) {
    /* if .py is passed, check the pyo version first */
    strcpy(entrypoint, env_entrypoint);
    entrypoint[strlen(env_entrypoint) + 1] = '\0';
#if PY_MAJOR_VERSION > 2
    entrypoint[strlen(env_entrypoint)] = 'c';
#else
    entrypoint[strlen(env_entrypoint)] = 'o';
#endif
    if (!file_exists(entrypoint)) {
      /* fallback on pure python version */
      if (!file_exists(env_entrypoint)) {
        LOGP("Entrypoint not found (.py), abort.");
        return -1;
      }
      strcpy(entrypoint, env_entrypoint);
    }
  } else {
    LOGP("Entrypoint have an invalid extension (must be .py or .pyc/.pyo), abort.");
    return -1;
  }
  // LOGP("Entrypoint is:");
  // LOGP(entrypoint);
  fd = fopen(entrypoint, "r");
  if (fd == NULL) {
    LOGP("Open the entrypoint failed");
    LOGP(entrypoint);
    return -1;
  }

  /* run python !
   */
  ret = PyRun_SimpleFile(fd, entrypoint);
  fclose(fd);

  if (PyErr_Occurred() != NULL) {
    ret = 1;
    PyErr_Print(); /* This exits with the right code if SystemExit. */
    PyObject *f = PySys_GetObject("stdout");
    if (PyFile_WriteString(
            "\n", f)) /* python2 used Py_FlushLine, but this no longer exists */
      PyErr_Clear();
  }

  LOGP("Python for android ended.");

  /* Shut down: since regular shutdown causes issues sometimes
     (seems to be an incomplete shutdown breaking next launch)
     we'll use sys.exit(ret) to shutdown, since that one works.

     Reference discussion:

     https://github.com/kivy/kivy/pull/6107#issue-246120816
   */
  char terminatecmd[256];
  snprintf(
    terminatecmd, sizeof(terminatecmd),
    "import sys; sys.exit(%d)\n", ret
  );
  PyRun_SimpleString(terminatecmd);

  /* This should never actually be reached, but we'll leave the clean-up
   * here just to be safe.
   */
#if PY_MAJOR_VERSION < 3
  Py_Finalize();
  LOGP("Unexpectedly reached Py_FinalizeEx(), but was successful.");
#else
  if (Py_FinalizeEx() != 0)  // properly check success on Python 3
    LOGP("Unexpectedly reached Py_FinalizeEx(), and got error!");
  else
    LOGP("Unexpectedly reached Py_FinalizeEx(), but was successful.");
#endif

  return ret;
}
Exemple #29
0
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();
}
Exemple #30
0
int main(int argc, char* argv[]) {
    if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
        printf("Failed to init SDL\n");
        return 1;
    }

    if (SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_OPENGL) == NULL) {
        printf("Failed to set video mode\n");
        return 1;
    }

    if (initGL() == 1) {
        printf("Failed to init OpenGL\n");
        return 1;
    }

    SDL_WM_SetCaption("Exciting Things", NULL);

    // set up the quads we will be rendering 
    /*quad quads[NUM_QUADS];
    int i = 0;
    point q1_center, q1_bl, q1_tr,
          q2_center, q2_bl, q2_tr,
          q3_center, q3_bl, q3_tr;
    rgb_color color;
    q1_center.x = 200; q1_center.y = 200;
    q1_bl.x = -50.0f; q1_bl.y = -50.0f;
    q1_tr.x = 50.0f; q1_tr.y = 50.0f;
    color.r = 1.0f; color.g = 0.0f; color.b = 0.0f;
    quads[0].center = q1_center;
    quads[0].bottom_left = q1_bl;
    quads[0].top_right = q1_tr;
    quads[0].color = color;*/


    // objects for running a python script
    PyObject *script_module, *ret_obj, *mod_func, *args;
    // pointer for array we will dump script results in
    quad *quads;
    int num_quads;

    printf("Initializing Python\n");
    Py_Initialize();
    PySys_SetPath(".");
    printf("Importing modules\n");
    script_module = PyImport_ImportModule("scripts");
    mod_func = PyObject_GetAttrString(script_module, "create_quads");
    // this is where we call the python script
    ret_obj = PyEval_CallObject(mod_func, NULL);
    // translate and store quad objects
    if (ret_obj == NULL) {
        printf("Failed to retrieve quads\n");
        return 1;
    }
    num_quads = translate_quads(&quads, ret_obj);

    // run the main loop
    int running = 1;
    SDL_Event event;
    while(running) {
        while(SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) {
                running = 0;
            } else if (event.type == SDL_KEYDOWN) {
                //pass
            }
        }
        render(quads, num_quads);
    }
    free(quads);
    Py_Finalize();


    return 0;
}