Exemplo n.º 1
0
/* Loads a file into a module; it is not inserted into sys.modules */
static int py_load_module(PyObject *module, const char *path) 
{
    PyObject *dict, *ret, *fp;

    if (PyModule_AddStringConstant(module, "__file__", (char *)path) < 0)
        return 0;
    
    dict = PyModule_GetDict(module);
    
    if (PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins()) < 0)
        return 0;

    /* Dont use the standard library to avoid incompatabilities with 
       the FILE structure and Python */
    fp = PyFile_FromString((char *)path, "r");
    if (!fp)
        return 0;

    ret = PyRun_File(PyFile_AsFile(fp), path, Py_file_input, dict, dict);
    Py_DECREF(fp);  /* XXX: I assume that the file is closed when refs drop to zero? */ 
    if (!ret)
        return 0;

    Py_DECREF(ret);
    return 1;

}
// Execute python source code from file filename.
// global and local are the global and local scopes respectively,
// used during execution.
object BOOST_PYTHON_DECL exec_file(str filename, object global, object local)
{
  // Set suitable default values for global and local dicts.
  object none;
  if (global.ptr() == none.ptr())
  {
    if (PyObject *g = PyEval_GetGlobals())
      global = object(detail::borrowed_reference(g));
    else
      global = dict();
  }
  if (local.ptr() == none.ptr()) local = global;
  // should be 'char const *' but older python versions don't use 'const' yet.
  char *f = python::extract<char *>(filename);
  // Let python open the file to avoid potential binary incompatibilities.
  PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r"));
  if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file");
  python::handle<> file(pyfile);
  PyObject* result = PyRun_File(PyFile_AsFile(file.get()),
                f,
                Py_file_input,
                global.ptr(), local.ptr());
  if (!result) throw_error_already_set();
  return object(detail::new_reference(result));
}
Exemplo n.º 3
0
// Execute python source code from file filename.
// global and local are the global and local scopes respectively,
// used during execution.
object BOOST_PYTHON_DECL exec_file(str filename, object global, object local)
{
    // Set suitable default values for global and local dicts.
    if (global.is_none())
    {
        if (PyObject *g = PyEval_GetGlobals())
            global = object(detail::borrowed_reference(g));
        else
            global = dict();
    }
    if (local.is_none()) local = global;
    // should be 'char const *' but older python versions don't use 'const' yet.
    char *f = python::extract<char *>(filename);
#if PY_VERSION_HEX >= 0x03000000
    // TODO(bhy) temporary workaround for Python 3.
    // should figure out a way to avoid binary incompatibilities as the Python 2
    // version did.
    FILE *fs = fopen(f, "r");
#else
    // Let python open the file to avoid potential binary incompatibilities.
    PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r"));
    if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file");
    python::handle<> file(pyfile);
    FILE *fs = PyFile_AsFile(file.get());
#endif
    PyObject* result = PyRun_File(fs,
                                  f,
                                  Py_file_input,
                                  global.ptr(), local.ptr());
    if (!result) throw_error_already_set();
    return object(detail::new_reference(result));
}
Exemplo n.º 4
0
bool PythonInterpreter::runScript(const char* filename, const char* shortName) {
    PyEval_RestoreThread(state);

    PyObject* script = PyFile_FromString(const_cast<char*>(filename),
        const_cast<char*>("r"));
    if (script) {
        PyObject* ans = PyRun_File(PyFile_AsFile(script),
            const_cast<char*>(shortName),
            Py_file_input, mainNamespace, mainNamespace);
        Py_DECREF(script);

        if (ans) {
            Py_DECREF(ans);
            state = PyEval_SaveThread();
            return true;
        } else {
            PyErr_Print();
            state = PyEval_SaveThread();
            return false;
        }
    } else {
        state = PyEval_SaveThread();
        return false;
    }
}
Exemplo n.º 5
0
bool run_script(const QString &fn)
{
  QString filename=exe_dir.filePath(fn);
  #ifdef _WIN32
    FILE *file=_wfopen(filename.utf16(), L"r");
  #else
    FILE *file=fopen(filename.toUtf8(), "r");
  #endif
  if (file)
  {
    pycon("Starting script %S", filename.unicode());

    PyObject *mod=PyImport_AddModule("__main__");
    PyObject *modDict=PyModule_GetDict(mod);

    PyObject *o=PyRun_File(file, qPrintable(filename), Py_file_input, modDict, modDict);
    fclose(file);
    Py_XDECREF(o);

    if (PyErr_Occurred())
    {
      PyErr_Print();
      return false;
    }

    return true;
  }
  else
  {
    pycon("Failed to open script file %S", filename.unicode());
    return false;
  }
}
void Python_group_script::execute(const std::string grid_name, const std::string group_name) const
{
	PyRun_SimpleString(""
		"import redirect\n"
		"class CoutLogger:\n"
		"    def __init__(self):\n"
		"        self.buf = []\n"
		"    def write(self, data):\n"
		"        self.buf.append(data)\n"
		"        if data.endswith('\\n'):\n"
		"            redirect.sgems_cout(''.join(self.buf))\n"
		"            self.buf = []\n"
		"\n"
		"class CerrLogger:\n"
		"    def __init__(self):\n"
		"        self.buf = []\n"
		"    def write(self, data):\n"
		"        self.buf.append(data)\n"
		"        if data.endswith('\\n'):\n"
		"            redirect.sgems_cerr(''.join(self.buf))\n"
		"            self.buf = []\n"
		"\n"
		"import sys\n"
		"sys.stdout = CoutLogger()\n"
		"sys.stderr = CerrLogger()\n"
		"");

	FILE* fp = fopen(filename_.c_str(), "r");
	if (!fp)
	{
		GsTLcerr << "can't open file " << filename_ << gstlIO::end;
		return;
	}

	PyObject* module = PyImport_AddModule("__main__");
	PyObject* dictionary = PyModule_GetDict(module);
	PyObject* dictionary_copy = PyDict_Copy(dictionary);

	PyRun_File(fp, filename_.c_str(), Py_file_input, dictionary_copy, dictionary_copy);

	PyObject* function = PyDict_GetItemString(dictionary_copy, "sgems_execute_group_action");
	if (PyCallable_Check(function))
	{
		PyObject* result = PyObject_CallFunction(function, "ss", grid_name.c_str(), group_name.c_str());

		//		if (NULL == result)
		//		{
		//			std::cout << "execution failed\n";
		//		}

		Py_XDECREF(result);
	}

	Py_XDECREF(dictionary_copy);
	fclose(fp);
}
Exemplo n.º 7
0
static void
python_plugin_execute (const gchar   *filename,
		       PlannerWindow *window,
		       GHashTable    *scripts)
{
	PlannerPythonEnv *env;
	FILE             *fp;
	PyObject         *pModule;
	PyObject         *py_object;

	env = planner_python_env_new (filename);

	pModule = PyRun_String ("import pygtk\n"
				"pygtk.require('2.0')\n"
				"import gtk\n"
				"import planner\n",
				Py_file_input, env->globals, env->globals);
	if (!pModule) {
		PyErr_Print ();
		planner_python_env_free (env);
		return;
	}

	pModule = PyImport_ImportModuleEx ("plannerui", env->globals, env->globals, Py_None);
	if (!pModule) {
		PyErr_Print ();
		planner_python_env_free (env);
		return;
	}

	py_object = pygobject_new (G_OBJECT (window));
	PyDict_SetItemString (env->globals, "window", py_object);
	Py_DECREF (py_object);

	py_object = pygobject_new (G_OBJECT (planner_window_get_application (window)));
	PyDict_SetItemString (env->globals, "application", py_object);
	Py_DECREF (py_object);

	fp = fopen (filename,"r");
	if (fp) {
		if (PyRun_File (fp, (gchar *) filename, Py_file_input, env->globals, env->globals) == NULL) {
			PyErr_Print ();
		}
		fclose (fp);
		g_hash_table_insert (scripts, env->filename, env);
	} else {
		planner_python_env_free (env);

		/* FIXME: do the free */
		g_warning ("Could not open python script: %s", filename);
	}
}
Exemplo n.º 8
0
bool PythonEngine::runFile(const std::string& filePath) {
#ifdef OSGWIDGET_USEPYTHON
    if(!osgDB::fileExists(filePath)) {
        warn()
            << "Couldn't find file \"" << filePath << "\" for PythonEngine."
            << std::endl
        ;

        return false;
    }

    FILE*     f = fopen(filePath.c_str(), "r");
    PyObject* r = PyRun_File(f, filePath.c_str(), Py_file_input, _data->main, _data->main);

    fclose(f);

    if(!r) {
        r = PyErr_Occurred();

        if(r) {
            // The following snippet lets us get the return code. That is: if the
            // script is stopped with sys.exit() or similar. We could use this
            // return code to do something sensible... later.
            if(PyErr_ExceptionMatches(PyExc_SystemExit)) {
                PyObject* ty = 0;
                PyObject* er = 0;
                PyObject* tr = 0;

                PyErr_Fetch(&ty, &er, &tr);

                Py_DECREF(ty);
                Py_DECREF(er);
                Py_DECREF(er);
            }

            else {
                PyErr_Print();
                PyErr_Clear();
            }
        }

        return false;
    }

    return true;

#else
    return noPythonFail("Can't evaluate code in PythonEngine");
#endif
}
Exemplo n.º 9
0
// Execute python source code from file filename.
// global and local are the global and local scopes respectively,
// used during execution.
object BOOST_PYTHON_DECL exec_file(str filename, object global, object local)
{
  // should be 'char const *' but older python versions don't use 'const' yet.
  char *f = python::extract<char *>(filename);
  // Let python open the file to avoid potential binary incompatibilities.
  PyObject *pyfile = PyFile_FromString(f, "r");
  if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file");
  python::handle<> file(pyfile);
  PyObject* result = PyRun_File(PyFile_AsFile(file.get()),
                f,
                Py_file_input,
                global.ptr(), local.ptr());
  if (!result) throw_error_already_set();
  return object(detail::new_reference(result));
}
Exemplo n.º 10
0
bool PythonModule::private_load(const char *fullname) {
  FILE *script = fopen(fullname,"r");
  if(!script) {
      return false;
  }

  set_interpreter_name();

  PyObject *ret = PyRun_File(script, fullname, Py_file_input, my_namespace, my_namespace);
  if(ret == NULL) {
      PyErr_Print();
      fclose(script);

      return false;
  }
  Py_XDECREF(ret);
  fclose(script);

  return true;
}
Exemplo n.º 11
0
int run_code(int val){
//int main(void){
    int ret = 0;
    PyObject* retval;

    Py_Initialize();
    PyRun_SimpleString("print('hello word from embedded python')");

    PyObject* main_mod = PyImport_AddModule("__main__");
    PyObject* main_dic = PyModule_GetDict(main_mod);

    const char *script_name = "hello.py";
    FILE* script = fopen(script_name,"r");

    retval = PyImport_ImportModule("numpy");
//    retval = PyImport_ImportModuleEx("numpy", main_dic, main_dic, NULL);
    if(!retval) goto py_error;

    retval = PyRun_File(script, script_name, Py_file_input, main_dic, main_dic);
    if(!retval) goto py_error;

/*
    PyObject* retobj = PyRun_String("foo(11)", Py_eval_input, main_dic, main_dic);
    long retval = PyLong_AsLong(retobj);
*/

    py_exit:
        Py_Finalize();
        return ret;

    py_error:
        ret = -1;
        printf("exception in script !?");
        PyErr_PrintEx(0);
        goto py_exit;

}
Exemplo n.º 12
0
bool PythonTools::initialize()
{
    Py_Initialize();
    main_m = PyImport_AddModule( "__main__" );
    main_d = PyModule_GetDict( main_m );

    gravUtil* util = gravUtil::getInstance();
    entryModule = util->findFile( "gravEntry.py" );
    entryFunc = "entryFunc";

    bool ret = false;
    if ( entryModule.compare( "" ) != 0 )
    {
        FILE* file_1 = fopen( entryModule.c_str(), "r" );
        bool open = file_1 != NULL;
        if ( open )
        {
            PyRun_File( file_1, entryModule.c_str(), Py_file_input, main_d,
                            main_d );
            fclose( file_1 );
            ret = true;
        }
        else
        {
            gravUtil::logWarning( "PythonTools::init: failed to open %s\n",
                        entryModule.c_str() );
        }
    }
    else
    {
        gravUtil::logWarning( "PythonTools::init: entry script not found - "
                "python integration not available\n" );
    }

    return ret;
}
Exemplo n.º 13
0
void Python_script::execute(const std::string grid_name, const std::vector<std::string> prop_names) const
{

	PyRun_SimpleString(""
		"import redirect\n"
		"class CoutLogger:\n"
		"    def __init__(self):\n"
		"        self.buf = []\n"
		"    def write(self, data):\n"
		"        self.buf.append(data)\n"
		"        if data.endswith('\\n'):\n"
		"            redirect.sgems_cout(''.join(self.buf))\n"
		"            self.buf = []\n"
		"\n"
		"class CerrLogger:\n"
		"    def __init__(self):\n"
		"        self.buf = []\n"
		"    def write(self, data):\n"
		"        self.buf.append(data)\n"
		"        if data.endswith('\\n'):\n"
		"            redirect.sgems_cerr(''.join(self.buf))\n"
		"            self.buf = []\n"
		"\n"
		"import sys\n"
		"sys.stdout = CoutLogger()\n"
		"sys.stderr = CerrLogger()\n"
		"");

	FILE* fp = fopen(filename_.c_str(), "r");
	if (!fp)
	{
		GsTLcerr << "can't open file " << filename_ << gstlIO::end;
		return;
	}

	PyObject* module = PyImport_AddModule("__main__");
	PyObject* dictionary = PyModule_GetDict(module);
	PyObject* dictionary_copy = PyDict_Copy(dictionary);

	PyRun_File(fp, filename_.c_str(), Py_file_input, dictionary_copy, dictionary_copy);

	PyObject* function = PyDict_GetItemString(dictionary_copy, "sgems_execute_action");
	if (PyCallable_Check(function))
	{
		//		PyObject* properties = Py_BuildValue("[ss]", prop_names.at(0).c_str(), prop_names.at(0).c_str());
		//		if (NULL == properties)
		//		{
		//			std::cout << "building value failed\n";
		//		}
		//		PyObject* properties = PyList_New(prop_names.size());
		//		for (int i = 0; i < prop_names.size(); ++i)
		//		{
		//			PyList_SetItem(properties, i, PyString_FromString(prop_names.at(i).c_str()));
		//		}
		//		PyObject* result = PyObject_CallFunction(function, "s[o]", grid_name.c_str(), properties);

		PyObject* result = NULL;

		switch (prop_names.size())
		{
		case 1:
			result = PyObject_CallFunction(function, "s[s]", grid_name.c_str(), prop_names.at(0).c_str());
			break;
		case 2:
			result = PyObject_CallFunction(function, "s[ss]", grid_name.c_str(), prop_names.at(0).c_str(), prop_names.at(1).c_str());
			break;
		default:
			GsTLcerr << "Execution of python script failed.\n Cannot have more than 2 properties selected\n" << gstlIO::end;
			break;
		}

		//		if (NULL == result)
		//		{
		//			std::cout << "execution failed\n";
		//		}

		Py_XDECREF(result);
	}

	Py_XDECREF(dictionary_copy);
	fclose(fp);
}
Exemplo n.º 14
0
static int python_script_exec(bContext *C, const char *fn, struct Text *text,
                              struct ReportList *reports, const short do_jump)
{
	PyObject *main_mod = NULL;
	PyObject *py_dict = NULL, *py_result = NULL;
	PyGILState_STATE gilstate;

	BLI_assert(fn || text);

	if (fn == NULL && text == NULL) {
		return 0;
	}

	bpy_context_set(C, &gilstate);

	PyC_MainModule_Backup(&main_mod);

	if (text) {
		char fn_dummy[FILE_MAXDIR];
		bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);

		if (text->compiled == NULL) {   /* if it wasn't already compiled, do it now */
			char *buf = txt_to_buf(text);

			text->compiled = Py_CompileString(buf, fn_dummy, Py_file_input);

			MEM_freeN(buf);

			if (PyErr_Occurred()) {
				if (do_jump) {
					python_script_error_jump_text(text);
				}
				BPY_text_free_code(text);
			}
		}

		if (text->compiled) {
			py_dict = PyC_DefaultNameSpace(fn_dummy);
			py_result =  PyEval_EvalCode(text->compiled, py_dict, py_dict);
		}

	}
	else {
		FILE *fp = BLI_fopen(fn, "r");

		if (fp) {
			py_dict = PyC_DefaultNameSpace(fn);

#ifdef _WIN32
			/* Previously we used PyRun_File to run directly the code on a FILE
			 * object, but as written in the Python/C API Ref Manual, chapter 2,
			 * 'FILE structs for different C libraries can be different and
			 * incompatible'.
			 * So now we load the script file data to a buffer */
			{
				char *pystring;

				fclose(fp);

				pystring = MEM_mallocN(strlen(fn) + 32, "pystring");
				pystring[0] = '\0';
				sprintf(pystring, "exec(open(r'%s').read())", fn);
				py_result = PyRun_String(pystring, Py_file_input, py_dict, py_dict);
				MEM_freeN(pystring);
			}
#else
			py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
			fclose(fp);
#endif
		}
		else {
			PyErr_Format(PyExc_IOError,
			             "Python file \"%s\" could not be opened: %s",
			             fn, strerror(errno));
			py_result = NULL;
		}
	}

	if (!py_result) {
		if (text) {
			if (do_jump) {
				python_script_error_jump_text(text);
			}
		}
		BPy_errors_to_report(reports);
	}
	else {
		Py_DECREF(py_result);
	}

	if (py_dict) {
#ifdef PYMODULE_CLEAR_WORKAROUND
		PyModuleObject *mmod = (PyModuleObject *)PyDict_GetItemString(PyThreadState_GET()->interp->modules, "__main__");
		PyObject *dict_back = mmod->md_dict;
		/* freeing the module will clear the namespace,
		 * gives problems running classes defined in this namespace being used later. */
		mmod->md_dict = NULL;
		Py_DECREF(dict_back);
#endif

#undef PYMODULE_CLEAR_WORKAROUND
	}

	PyC_MainModule_Restore(main_mod);

	bpy_context_clear(C, &gilstate);

	return (py_result != NULL);
}
Exemplo n.º 15
0
int script_run(ATM* atm, SESSION_STATE * session,
		const gchar* extra_code)
{
	/* (Tomas) this mutex is a very bad idea, but there's no better solution
	 *  with this implementation
	 */
	PyObject * ret, * err, * dict;
	int r = TRUE;
	

	g_static_mutex_lock(&mutex);	// serialize the scripts execution 
	current_session = session;

	dict = PyDict_New ();
	PyErr_Clear ();
	if (dict && extra_code) {
		ret = PyRun_String(extra_code, Py_file_input, p_main_dict, dict);
		//g_print(">>extra code:\n%s\n>>end extra code\n",
		//	extra_code);
		Py_XDECREF (ret);
	}

	err = PyErr_Occurred ();
	if (!err) {
		ret = NULL;
        if (atm->text) {
			ret = PyRun_String (atm->text, Py_file_input, p_main_dict, dict);
        } else if (atm->source) {
			FILE *fd;
			fd = fopen(atm->source, "r");
			if (fd) {
				ret = PyRun_File(fd, atm->source, Py_file_input, p_main_dict, dict);
				fclose(fd);
			} else {
				char buf [1024];
				g_snprintf (buf, 1024, "%s: %s", atm->source, strerror (errno));
				atm->errors = g_list_append (atm->errors, g_strdup (buf));
				//se = g_strdup (buf);
			}
		}
		err = PyErr_Occurred ();
		Py_XDECREF (ret);
	}
	if (err) {
		PyObject * type, * val, * trback, * pystr = NULL;
		char * c;

		r = FALSE;
		PyErr_Fetch (&type, &val, &trback);
		if (val) {
			pystr = PyObject_Str (val);
		} else if (type) {
			pystr = PyObject_Str (val);
		}
		if (pystr) {
			c = PyString_AsString (pystr);
		} else {
			c = "<unknown error>";
		}
		atm->errors = g_list_append (atm->errors, g_strdup (c));
		Py_XDECREF (type);
		Py_XDECREF (val);
		Py_XDECREF (trback);
		Py_XDECREF (pystr);
	}

	Py_XDECREF (dict);

	g_static_mutex_unlock(&mutex);

	return r;
}
Exemplo n.º 16
0
bool get_plots(const std::string& python_file, std::vector<Plot>& plots) {

    plots.clear();

    std::FILE* f = std::fopen(python_file.c_str(), "r");
    if (!f) {
        std::cerr << "Failed to open '" << python_file << "'" <<std::endl;
        return false;
    }

    const std::string PLOTS_KEY_NAME = "plots";

    // Get a reference to the main module
    // and global dictionary
    PyObject* main_module = PyImport_AddModule("__main__");
    PyObject* global_dict = PyModule_GetDict(main_module);

    // If PyROOT is used inside the script, it performs some cleanups when the python env. is destroyed. This cleanup makes ROOT unusable afterwards.
    // The cleanup function is registered with the `atexit` module.
    // The solution is to not execute the cleanup function. For that, before destroying the python env, we check the list of exit functions,
    // and delete the one from PyROOT if found

    // Ensure the module is loaded
    PyObject* atexit_module = PyImport_ImportModule("atexit");

    // Execute the script
    PyObject* script_result = PyRun_File(f, python_file.c_str(), Py_file_input, global_dict, global_dict);

    if (! script_result) {
        PyErr_Print();
        return false;
    } else {
        PyObject* py_plots = PyDict_GetItemString(global_dict, "plots");
        if (!py_plots) {
            std::cerr << "No 'plots' variable declared in python script" << std::endl;
            return false;
        }

        if (! PyList_Check(py_plots)) {
            std::cerr << "The 'plots' variable is not a list" << std::endl;
            return false;
        }

        size_t l = PyList_Size(py_plots);
        if (! l)
            return true;

        for (size_t i = 0; i < l; i++) {
            PyObject* item = PyList_GetItem(py_plots, i);

            Plot plot;
            if (plot_from_PyObject(item, plot)) {
                plots.push_back(plot);
            }
        }
    }

    PyObject* atexit_exithandlers = PyObject_GetAttrString(atexit_module, "_exithandlers");
    for (size_t i = 0; i < PySequence_Size(atexit_exithandlers); i++) {
        PyObject* tuple = PySequence_GetItem(atexit_exithandlers, i);
        PyObject* f = PySequence_GetItem(tuple, 0);
        PyObject* module = PyFunction_GetModule(f);

        if (module && strcmp(PyString_AsString(module), "ROOT") == 0) {
            PySequence_DelItem(atexit_exithandlers, i);
            break;
        }
    }

    return true;
}
Exemplo n.º 17
0
static bool python_script_exec(
        bContext *C, const char *fn, struct Text *text,
        struct ReportList *reports, const bool do_jump)
{
	Main *bmain_old = CTX_data_main(C);
	PyObject *main_mod = NULL;
	PyObject *py_dict = NULL, *py_result = NULL;
	PyGILState_STATE gilstate;

	BLI_assert(fn || text);

	if (fn == NULL && text == NULL) {
		return 0;
	}

	bpy_context_set(C, &gilstate);

	PyC_MainModule_Backup(&main_mod);

	if (text) {
		char fn_dummy[FILE_MAXDIR];
		bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);

		if (text->compiled == NULL) {   /* if it wasn't already compiled, do it now */
			char *buf;
			PyObject *fn_dummy_py;

			fn_dummy_py = PyC_UnicodeFromByte(fn_dummy);

			buf = txt_to_buf(text);
			text->compiled = Py_CompileStringObject(buf, fn_dummy_py, Py_file_input, NULL, -1);
			MEM_freeN(buf);

			Py_DECREF(fn_dummy_py);

			if (PyErr_Occurred()) {
				if (do_jump) {
					python_script_error_jump_text(text);
				}
				BPY_text_free_code(text);
			}
		}

		if (text->compiled) {
			py_dict = PyC_DefaultNameSpace(fn_dummy);
			py_result =  PyEval_EvalCode(text->compiled, py_dict, py_dict);
		}

	}
	else {
		FILE *fp = BLI_fopen(fn, "r");

		if (fp) {
			py_dict = PyC_DefaultNameSpace(fn);

#ifdef _WIN32
			/* Previously we used PyRun_File to run directly the code on a FILE
			 * object, but as written in the Python/C API Ref Manual, chapter 2,
			 * 'FILE structs for different C libraries can be different and
			 * incompatible'.
			 * So now we load the script file data to a buffer */
			{
				const char *pystring =
				        "ns = globals().copy()\n"
				        "with open(__file__, 'rb') as f: exec(compile(f.read(), __file__, 'exec'), ns)";

				fclose(fp);

				py_result = PyRun_String(pystring, Py_file_input, py_dict, py_dict);
			}
#else
			py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
			fclose(fp);
#endif
		}
		else {
			PyErr_Format(PyExc_IOError,
			             "Python file \"%s\" could not be opened: %s",
			             fn, strerror(errno));
			py_result = NULL;
		}
	}

	if (!py_result) {
		if (text) {
			if (do_jump) {
				/* ensure text is valid before use, the script may have freed its self */
				Main *bmain_new = CTX_data_main(C);
				if ((bmain_old == bmain_new) && (BLI_findindex(&bmain_new->text, text) != -1)) {
					python_script_error_jump_text(text);
				}
			}
		}
		BPy_errors_to_report(reports);
	}
	else {
		Py_DECREF(py_result);
	}

	if (py_dict) {
#ifdef PYMODULE_CLEAR_WORKAROUND
		PyModuleObject *mmod = (PyModuleObject *)PyDict_GetItemString(PyThreadState_GET()->interp->modules, "__main__");
		PyObject *dict_back = mmod->md_dict;
		/* freeing the module will clear the namespace,
		 * gives problems running classes defined in this namespace being used later. */
		mmod->md_dict = NULL;
		Py_DECREF(dict_back);
#endif

#undef PYMODULE_CLEAR_WORKAROUND
	}

	PyC_MainModule_Restore(main_mod);

	bpy_context_clear(C, &gilstate);

	return (py_result != NULL);
}
Exemplo n.º 18
0
/* Would be nice if python had this built in */
void PyC_RunQuicky(const char *filepath, int n, ...)
{
	FILE *fp= fopen(filepath, "r");

	if(fp) {
		PyGILState_STATE gilstate= PyGILState_Ensure();

		va_list vargs;	

		int *sizes= PyMem_MALLOC(sizeof(int) * (n / 2));
		int i;

		PyObject *py_dict = PyC_DefaultNameSpace(filepath);
		PyObject *values= PyList_New(n / 2); /* namespace owns this, dont free */

		PyObject *py_result, *ret;

		PyObject *struct_mod= PyImport_ImportModule("struct");
		PyObject *calcsize= PyObject_GetAttrString(struct_mod, "calcsize"); /* struct.calcsize */
		PyObject *pack= PyObject_GetAttrString(struct_mod, "pack"); /* struct.pack */
		PyObject *unpack= PyObject_GetAttrString(struct_mod, "unpack"); /* struct.unpack */

		Py_DECREF(struct_mod);

		va_start(vargs, n);
		for (i=0; i * 2<n; i++) {
			char *format = va_arg(vargs, char *);
			void *ptr = va_arg(vargs, void *);

			ret= PyObject_CallFunction(calcsize, (char *)"s", format);

			if(ret) {
				sizes[i]= PyLong_AsSsize_t(ret);
				Py_DECREF(ret);
				ret = PyObject_CallFunction(unpack, (char *)"sy#", format, (char *)ptr, sizes[i]);
			}

			if(ret == NULL) {
				printf("PyC_InlineRun error, line:%d\n", __LINE__);
				PyErr_Print();
				PyErr_Clear();

				PyList_SET_ITEM(values, i, Py_None); /* hold user */
				Py_INCREF(Py_None);

				sizes[i]= 0;
			}
			else {
				if(PyTuple_GET_SIZE(ret) == 1) {
					/* convenience, convert single tuples into single values */
					PyObject *tmp= PyTuple_GET_ITEM(ret, 0);
					Py_INCREF(tmp);
					Py_DECREF(ret);
					ret = tmp;
				}

				PyList_SET_ITEM(values, i, ret); /* hold user */
			}
		}
		va_end(vargs);
		
		/* set the value so we can access it */
		PyDict_SetItemString(py_dict, "values", values);

		py_result = PyRun_File(fp, filepath, Py_file_input, py_dict, py_dict);

		fclose(fp);

		if(py_result) {

			/* we could skip this but then only slice assignment would work
			 * better not be so strict */
			values= PyDict_GetItemString(py_dict, "values");

			if(values && PyList_Check(values)) {

				/* dont use the result */
				Py_DECREF(py_result);
				py_result= NULL;

				/* now get the values back */
				va_start(vargs, n);
				for (i=0; i*2 <n; i++) {
					char *format = va_arg(vargs, char *);
					void *ptr = va_arg(vargs, void *);
					
					PyObject *item;
					PyObject *item_new;
					/* prepend the string formatting and remake the tuple */
					item= PyList_GET_ITEM(values, i);
					if(PyTuple_CheckExact(item)) {
						int ofs= PyTuple_GET_SIZE(item);
						item_new= PyTuple_New(ofs + 1);
						while(ofs--) {
							PyObject *member= PyTuple_GET_ITEM(item, ofs);
							PyTuple_SET_ITEM(item_new, ofs + 1, member);
							Py_INCREF(member);
						}

						PyTuple_SET_ITEM(item_new, 0, PyUnicode_FromString(format));
					}
					else {
						item_new= Py_BuildValue("sO", format, item);
					}

					ret = PyObject_Call(pack, item_new, NULL);

					if(ret) {
						/* copy the bytes back into memory */
						memcpy(ptr, PyBytes_AS_STRING(ret), sizes[i]);
						Py_DECREF(ret);
					}
					else {
						printf("PyC_InlineRun error on arg '%d', line:%d\n", i, __LINE__);
						PyC_ObSpit("failed converting:", item_new);
						PyErr_Print();
						PyErr_Clear();
					}

					Py_DECREF(item_new);
				}
				va_end(vargs);
			}
			else {
				printf("PyC_InlineRun error, 'values' not a list, line:%d\n", __LINE__);
			}
		}
Exemplo n.º 19
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();
}