Exemple #1
0
static PyObject *
builtin___import__(PyObject *self, PyObject *args)
{
	char *name;
	/* @@@ hack until I get ParseTuple working */
	name = ((PyStringObject *)(((PyTupleObject *)args)->ob_item[0]))->ob_sval;
	
	return PyImport_ImportModuleEx(name);
}
Exemple #2
0
static gboolean
eom_python_module_load (GTypeModule *gmodule)
{
	EomPythonModulePrivate *priv = EOM_PYTHON_MODULE_GET_PRIVATE (gmodule);
	PyObject *main_module, *main_locals, *locals, *key, *value;
	PyObject *module, *fromlist;
	Py_ssize_t pos = 0;

	g_return_val_if_fail (Py_IsInitialized (), FALSE);

	main_module = PyImport_AddModule ("__main__");

	if (main_module == NULL) {
		g_warning ("Could not get __main__.");
		return FALSE;
	}

	/* If we have a special path, we register it */
	if (priv->path != NULL) {
		PyObject *sys_path = PySys_GetObject ("path");
		PyObject *path = PyString_FromString (priv->path);

		if (PySequence_Contains(sys_path, path) == 0)
			PyList_Insert (sys_path, 0, path);

		Py_DECREF(path);
	}

	main_locals = PyModule_GetDict (main_module);

	/* We need a fromlist to be able to import modules with
         * a '.' in the name. */
	fromlist = PyTuple_New(0);

	module = PyImport_ImportModuleEx (priv->module, main_locals, main_locals, fromlist);

	Py_DECREF(fromlist);

	if (!module) {
		PyErr_Print ();
		return FALSE;
	}

	locals = PyModule_GetDict (module);

	while (PyDict_Next (locals, &pos, &key, &value)) {
		if (!PyType_Check(value))
			continue;

		if (PyObject_IsSubclass (value, (PyObject*) PyEomPlugin_Type)) {
			priv->type = eom_python_plugin_get_type (gmodule, value);
			return TRUE;
		}
	}

	return FALSE;
}
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);
	}
}
Exemple #4
0
void PythonModule::load(std::string script) {
    if(!initialised) {
        return;
    }
    block_threads();
    if(boost::algorithm::ends_with(script, ".py")) {
        if(!private_load(script.c_str())) {
            std::string s(name());
            s += std::string(" could not load ") + std::string(script);
            perror(s.c_str());
        }
    } else if(PyImport_ImportModuleEx(const_cast<char *>(script.c_str()), my_namespace, my_namespace, NULL)) {
        PyErr_Print();
    }
    unblock_threads();
}
Exemple #5
0
bool
QPython::importModule_sync(QString name)
{
    // Lesson learned: name.toUtf8().constData() doesn't work, as the
    // temporary QByteArray will be destroyed after constData() has
    // returned, so we need to save the toUtf8() result in a local
    // variable that doesn't get destroyed until the function returns.
    QByteArray utf8bytes = name.toUtf8();
    const char *moduleName = utf8bytes.constData();

    ENSURE_GIL_STATE;

    bool use_api_10 = (api_version_major == 1 && api_version_minor == 0);

    PyObjectRef module;

    if (use_api_10) {
        // PyOtherSide API 1.0 behavior (star import)
        module = PyObjectRef(PyImport_ImportModule(moduleName), true);
    } else {
        // PyOtherSide API 1.2 behavior: "import x.y.z"
        PyObjectRef fromList(PyList_New(0), true);
        module = PyObjectRef(PyImport_ImportModuleEx(const_cast<char *>(moduleName),
                    NULL, NULL, fromList.borrow()), true);
    }

    if (!module) {
        emitError(QString("Cannot import module: %1 (%2)").arg(name).arg(priv->formatExc()));
        return false;
    }

    if (!use_api_10) {
        // PyOtherSide API 1.2 behavior: "import x.y.z"
        // If "x.y.z" is imported, we need to set "x" in globals
        if (name.indexOf('.') != -1) {
            name = name.mid(0, name.indexOf('.'));
            utf8bytes = name.toUtf8();
            moduleName = utf8bytes.constData();
        }
    }

    PyDict_SetItemString(priv->globals.borrow(), moduleName, module.borrow());
    return true;
}
Exemple #6
0
    // decref handled internally
    PyObject* LoadModule(std::string moduleName) {
        PyObject* module = GetModule(moduleName);
        if(module)
            return module;

        char* unConstName = const_cast<char*>(moduleName.c_str()); // lol
        // seriously, python's api implementers didn't get the const right?
        // or they are actually modifying stuff...
        module = PyImport_ImportModuleEx(unConstName,
            /*globals*/ NULL, /*locals*/ NULL, /*fromlist*/ NULL);
        if(!module || !PyModule_Check(module)) {
            printf("Error loading module:%s\n", moduleName.c_str());
            PyErr_Print();
            if(module) { Py_DECREF(module); }
            return NULL;
        }
        _modules.insert(std::make_pair(moduleName, module));
        
        PyObject* dict = PyModule_GetDict(module); // borrowed reference
        _dictionaries.insert(std::make_pair(moduleName, dict));
        return module;
    }
static CeditPlugin *
cedit_plugin_loader_iface_load (CeditPluginLoader *loader,
				CeditPluginInfo   *info,
				const gchar       *path)
{
	CeditPluginLoaderPython *pyloader = CEDIT_PLUGIN_LOADER_PYTHON (loader);
	PyObject *main_module, *main_locals, *pytype;
	PyObject *pymodule, *fromlist;
	gchar *module_name;
	CeditPlugin *result;
	
	if (pyloader->priv->init_failed)
	{
		g_warning ("Cannot load python plugin Python '%s' since cedit was"
		           "not able to initialize the Python interpreter.",
		           cedit_plugin_info_get_name (info));
		return NULL;
	}
	
	/* see if py definition for the plugin is already loaded */
	result = new_plugin_from_info (pyloader, info);
	
	if (result != NULL)
		return result;
	
	main_module = PyImport_AddModule ("cedit.plugins");
	if (main_module == NULL)
	{
		g_warning ("Could not get cedit.plugins.");
		return NULL;
	}
	
	/* If we have a special path, we register it */
	if (path != NULL)
	{
		PyObject *sys_path = PySys_GetObject ("path");
		PyObject *pypath = PyString_FromString (path);

		if (PySequence_Contains (sys_path, pypath) == 0)
			PyList_Insert (sys_path, 0, pypath);

		Py_DECREF (pypath);
	}
	
	main_locals = PyModule_GetDict (main_module);
	
	/* we need a fromlist to be able to import modules with a '.' in the
	   name. */
	fromlist = PyTuple_New(0);
	module_name = g_strdup (cedit_plugin_info_get_module_name (info));
	
	pymodule = PyImport_ImportModuleEx (module_name, 
					    main_locals, 
					    main_locals, 
					    fromlist);
	
	Py_DECREF(fromlist);

	if (!pymodule)
	{
		g_free (module_name);
		PyErr_Print ();
		return NULL;
	}

	PyDict_SetItemString (main_locals, module_name, pymodule);
	g_free (module_name);
	
	pytype = find_python_plugin_type (info, pymodule);
	
	if (pytype)
		return add_python_info (pyloader, info, pymodule, path, pytype);

	return NULL;
}
Exemple #8
0
// constructor
PythonModule::PythonModule(
    sc_core::sc_module_name mn,
    const char* script_filename,
    int argc,
    char **argv) :
        sc_core::sc_module(mn),
        initialised(false),
        my_namespace(NULL),
        pysc_module(NULL),
        sys_path(NULL),
        name_py(NULL) {

    PYSC_INIT_MODULES();

    // set up interpreter and gs module and context object
    subscribe();
    block_threads();

    PYSC_PREPARE_MODULES();

#ifndef MTI_SYSTEMC
#if PY_MAJOR_VERSION >= 3
    wchar_t *args[argc];
    for(int i = 0; i< argc; i++) {
        args[i] = new wchar_t[strlen(argv[i])+1];
        mbstowcs(args[i], argv[i], strlen(argv[i])+1);
    }
    Py_SetProgramName(args[0]);
    if(script_filename && *script_filename) {
      delete args[0];
      args[0] = new wchar_t[strlen(script_filename)+1];
      mbstowcs(args[0], script_filename, strlen(script_filename)+1);
    }
    PySys_SetArgvEx(argc, args, 0);
#else
    char *args[argc];
    for(int i = 0; i< argc; i++) {
        args[i] = argv[i];
    }
    Py_SetProgramName(args[0]);
    if(script_filename && *script_filename) {
      args[0] = const_cast<char *>(script_filename);
    }
    PySys_SetArgvEx(argc, args, 0);
#endif

#else
    Py_SetProgramName("vsim");
    PySys_SetArgvEx(0, NULL, 0);
#endif

    // get a globals() dict for this PythonModule
    PyObject* main_module = PyImport_AddModule("__main__");  // borrowed ref
    if(!main_module) {
        PyErr_Print();
        unblock_threads();
        return;
    }
    my_namespace = PyModule_GetDict(main_module);  // borrowed ref
    my_namespace = PyDict_Copy(my_namespace);  // new ref

    sys_path = PySys_GetObject(const_cast<char *>("path"));  // new ref
    if(!sys_path) {
        PyErr_Print();
        unblock_threads();
        return;
    }

    initialised = true;

    // Now add the virtual env to the sys.path to load pysc and other socrocket modules
    unblock_threads();
#if defined(MTI_SYSTEMC) || defined(NC_SYSTEMC)
    boost::filesystem::path builddir = findPath("build", __FILE__);
#else
    std::map<std::string, std::string> *wafConfig = getWafConfig(argv[0]);
    std::string outdir = (*wafConfig)["out_dir"];
    outdir.erase(std::remove(outdir.begin(), outdir.end(), '\''), outdir.end());
    boost::filesystem::path builddir(outdir);
#endif
    boost::filesystem::path venvactivate(".conf_check_venv/bin/activate_this.py");
    std::string activate = (builddir/venvactivate).string();
    exec(
        "with open('"+activate+"') as script:\n" +
        "    code = compile(script.read(), '"+activate+"', 'exec')\n" +
        "    exec(code, dict(__file__='"+activate+"'))");
    block_threads();

    // make sure there's a reference to the pysc module available
    pysc_module = PyImport_ImportModuleEx(const_cast<char *>("usi"), my_namespace, my_namespace, NULL);
    if(!pysc_module) {
        PyErr_Print();
        unblock_threads();
        return;
    }

    // if we get to here, we consider ourselves initialised
    // note that:
    // - the namespace has no name, so is impossible to access from another PythonModule
    // - pysc and sys have been imported, but are not added to the namespace

    // tell the Python code it is embedded
    PyObject_SetAttrString(pysc_module, "__standalone__", Py_False);

    // tell the Python code its interpreter name
    name_py = PyString_FromString(name());  // new ref
    set_interpreter_name();
    unblock_threads();
    add_to_pythonpath(".");

    PythonModule::globalInstance = this;

    // run a script if one has been requested
    if (script_filename && *script_filename) {
      load(script_filename);
    }

#ifndef MTI_SYSTEMC
    sr_report_handler::handler = report_handler;
#endif
}
Exemple #9
0
bool obs_module_load()
{
    blog(LOG_INFO, "obs_module_load");
    //Need to init python here



    //load the swig  
    


    Py_Initialize();
    PyEval_InitThreads();
 
    

    /*Must set arguments for guis to work*/

    wchar_t* argv[] = { L"", NULL };
    int argc = sizeof(argv) / sizeof(wchar_t*) - 1;
  
    //SWIG_init();


    PySys_SetArgv(argc, argv);
   
    //need to add to directory

    PyRun_SimpleString("import os");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("os.environ['PYTHONUNBUFFERED'] = '1'");
    PyRun_SimpleString("sys.stdout = open('/dev/shm/stdOut.txt','w',1)");
    PyRun_SimpleString("sys.stderr = open('/dev/shm/stdErr.txt','w',1)");
    PyRun_SimpleString("print(sys.version)");





   /*Load a file*/
    
    
    PyObject* pName, *pModule, *pFunc,*argList;
    


    pName = PyUnicode_FromString("source");

    char script[] = "/scripts";
    const char *data_path = obs_get_module_data_path(obs_current_module());
    char *scripts_path = bzalloc(strlen(data_path)+strlen(script));
    strcpy(scripts_path,data_path);
    strcat(scripts_path,script);




    //Add the path to env
    add_to_python_path(scripts_path);
    bfree(scripts_path);


    //PyImport_AppendInittab("_libobs", PyInit_libobs);
    /*Import libobs*/

    
    //Py_XDECREF(main_module);


    //Add our custom stuff to libobs


    //import the script

    pModule = PyImport_Import(pName);
    pyHasError();
    //get the function by name
    if(pModule != NULL) {
      
      PyObject *ns = PyModule_GetDict(pModule);
      Py_INCREF(ns);
      PyObject *py_libobs = PyImport_ImportModuleEx("obspython",ns,ns,NULL);
      Py_INCREF(py_libobs);
      extend_swig_libobs(py_libobs);
      PyModule_AddObject(pModule,"obspython",py_libobs);
      
      pFunc = PyObject_GetAttr(pModule, PyUnicode_FromString("register"));
        if(pFunc != NULL) {
	  argList = Py_BuildValue("()");
            PyObject_CallObject(pFunc,argList);
 	     pyHasError();
	    Py_XDECREF(pFunc);
	    Py_XDECREF(argList);
        }
	Py_XDECREF(pModule);
    }
    Py_XDECREF(pName);
    
    



    //Not implemented yet?
    //obs_register_modal_ui(&myui);

    //Register this base class here
    obs_register_source(&python_source_info);
    


    //Release the thread gill
    PyThreadState* pts = PyGILState_GetThisThreadState();
    PyEval_ReleaseThread(pts);




    return true;
}