Exemple #1
1
//-------------------------------------------------------------------------------------
int Script::run_simpleString(const char* command, std::string* retBufferPtr)
{
	if(command == NULL)
	{
		ERROR_MSG("Script::Run_SimpleString: command is NULL!\n");
		return 0;
	}

	ScriptStdOutErrHook* pStdouterrHook = new ScriptStdOutErrHook();

	if(retBufferPtr != NULL)
	{
		DebugHelper::getSingleton().resetScriptMsgType();
		if(!pStdouterrHook->install()){												
			ERROR_MSG("Script::Run_SimpleString: pyStdouterrHook_->install() is failed!\n");
			SCRIPT_ERROR_CHECK();
			delete pStdouterrHook;
			return -1;
		}
			
		pStdouterrHook->setHookBuffer(retBufferPtr);
		//PyRun_SimpleString(command);

		PyObject *m, *d, *v;
		m = PyImport_AddModule("__main__");
		if (m == NULL)
		{
			SCRIPT_ERROR_CHECK();
			pStdouterrHook->uninstall();
			delete pStdouterrHook;
			return -1;
		}

		d = PyModule_GetDict(m);

		v = PyRun_String(command, Py_single_input, d, d);
		if (v == NULL) 
		{
			PyErr_Print();
			pStdouterrHook->uninstall();
			delete pStdouterrHook;
			return -1;
		}

		Py_DECREF(v);
		SCRIPT_ERROR_CHECK();
		
		pStdouterrHook->uninstall();
		delete pStdouterrHook;
		return 0;
	}

	PyRun_SimpleString(command);

	SCRIPT_ERROR_CHECK();
	delete pStdouterrHook;
	return 0;
}
Exemple #2
0
/**
   @param persist: If true, retain the Python interpreter,
                   else finalize it
   @param code: The multiline string of Python code.
                The last line is evaluated to the returned result
   @param output: Store result pointer here
   @return Tcl error code
 */
static int
python_eval(bool persist, const char* code, const char* expression,
            Tcl_Obj** output)
{
  int rc;
  char* result = python_result_default;

  // Initialize:
  rc = python_init();
  TCL_CHECK(rc);

  // Execute code:
  DEBUG_TCL_TURBINE("python: code: %s", code);
  PyObject* localDictionary = PyDict_New();
  PyRun_String(code, Py_file_input, main_dict, localDictionary);
  if (PyErr_Occurred()) return handle_python_exception();

  // Evaluate expression:
  DEBUG_TCL_TURBINE("python: expression: %s", expression);
  PyObject* o = PyRun_String(expression, Py_eval_input, main_dict, localDictionary);
  if (o == NULL) return handle_python_exception();

  // Convert Python result to C string, then to Tcl string:
  rc = PyArg_Parse(o, "s", &result);
  if (rc != 1) return handle_python_non_string(o);
  DEBUG_TCL_TURBINE("python: result: %s\n", result);
  *output = Tcl_NewStringObj(result, -1);

  // Clean up and return:
  Py_DECREF(o);
  if (!persist) python_finalize();
  return TCL_OK;
}
Exemple #3
0
void PythonEngine::init()
{
    m_isRunning = false;
    m_stdOut = "";

    // connect stdout
    connect(this, SIGNAL(pythonShowMessage(QString)), this, SLOT(stdOut(QString)));

    // init python
    Py_Initialize();

    // read functions
    m_functions = readFileContent(datadir() + "/functions.py");

    m_dict = PyDict_New();
    PyDict_SetItemString(m_dict, "__builtins__", PyEval_GetBuiltins());

    // init engine extensions
    Py_InitModule("pythonlab", pythonEngineFuntions);

    addCustomExtensions();

    // custom modules
    PyRun_String(QString("import sys; sys.path.insert(0, \"" + datadir() + "/resources/python" + "\")").toStdString().c_str(), Py_file_input, m_dict, m_dict);

    // functions.py
    PyRun_String(m_functions.toStdString().c_str(), Py_file_input, m_dict, m_dict);
}
Exemple #4
0
QStringList PythonEngine::codePyFlakes(const QString& fileName)
{
    QStringList out;

    QString exp = QString("result_pyflakes_pythonlab = python_engine_pyflakes_check(\"%1\")").arg(fileName);

    PyRun_String(exp.toLatin1().data(), Py_single_input, m_dict, m_dict);

    // parse result
    PyObject *result = PyDict_GetItemString(m_dict, "result_pyflakes_pythonlab");
    if (result)
    {
        Py_INCREF(result);
        PyObject *list;
        if (PyArg_Parse(result, "O", &list))
        {
            int count = PyList_Size(list);
            for (int i = 0; i < count; i++)
            {
                PyObject *item = PyList_GetItem(list, i);

                QString str = PyString_AsString(item);
                out.append(str);
            }
        }
        Py_DECREF(result);
    }

    PyRun_String("del result_pyflakes_pythonlab", Py_single_input, m_dict, m_dict);

    return out;
}
bool PythonScript::compile(bool for_eval)
{
  if(Context->isA("Table")) {
    PyDict_SetItemString(localDict,"__builtins__",PyDict_GetItemString(env()->globalDict(),"__builtins__"));
    PyObject *ret = PyRun_String("def col(c,*arg):\n\ttry: return self.cell(c,arg[0])\n\texcept(IndexError): return self.cell(c,i)\n",Py_file_input,localDict,localDict);
    if (ret)
      Py_DECREF(ret);
    else
      PyErr_Print();
  } else if(Context->isA("Matrix")) {
    PyDict_SetItemString(localDict,"__builtins__",PyDict_GetItemString(env()->globalDict(),"__builtins__"));
    PyObject *ret = PyRun_String("def cell(*arg):\n\ttry: return self.cell(arg[0],arg[1])\n\texcept(IndexError): return self.cell(i,j)\n",Py_file_input,localDict,localDict);
    if (ret)
      Py_DECREF(ret);
    else
      PyErr_Print();
  }
  bool success=false;
  Py_XDECREF(PyCode);
  PyCode = Py_CompileString(Code.ascii(),Name,Py_eval_input);
  if (PyCode) { // code is a single expression
    success = true;
  } else if (for_eval) { // code contains statements
    PyErr_Clear();
    PyObject *key, *value;
    int i=0;
    QString signature = "";
    while(PyDict_Next(localDict, &i, &key, &value))
      signature.append(PyString_AsString(key)).append(",");
    signature.truncate(signature.length()-1);
    QString fdef = "def __doit__("+signature+"):\n";
    fdef.append(Code);
    fdef.replace('\n',"\n\t");
    PyCode = Py_CompileString(fdef,Name,Py_file_input);
    if (PyCode)
    {
      PyObject *tmp = PyDict_New();
      Py_XDECREF(PyEval_EvalCode((PyCodeObject*)PyCode, env()->globalDict(), tmp));
      Py_DECREF(PyCode);
      PyCode = PyDict_GetItemString(tmp,"__doit__");
      Py_XINCREF(PyCode);
      Py_DECREF(tmp);
    }
    success = PyCode != NULL;
  } else {
    PyErr_Clear();
    PyCode = Py_CompileString(Code.ascii(),Name,Py_file_input);
    success = PyCode != NULL;
  }
  if (!success)
  {
    compiled = compileErr;
    emit_error(env()->errorMsg(), 0);
  } else
    compiled = isCompiled;
  return success;
}
Exemple #6
0
ExpressionResult PythonEngine::runPythonExpression(const QString &expression, bool returnValue)
{
    runPythonHeader();

    QString exp;
    if (returnValue)
        exp = QString("result_pythonlab = %1").arg(expression);
    else
        exp = expression;

    PyObject *output = PyRun_String(exp.toLatin1().data(), Py_single_input, m_dict, m_dict);

    ExpressionResult expressionResult;
    if (output)
    {
        PyObject *type = NULL, *value = NULL, *traceback = NULL, *str = NULL;
        PyErr_Fetch(&type, &value, &traceback);

        if (type != NULL && (str = PyObject_Str(type)) != NULL && (PyString_Check(str)))
        {
            Py_INCREF(str);
            expressionResult.error = PyString_AsString(str);
            Py_XDECREF(type);
            Py_XDECREF(str);
        }
        else
        {
            // parse result
            if (returnValue)
            {
                PyObject *result = PyDict_GetItemString(m_dict, "result_pythonlab");
                if (result)
                {
                    Py_INCREF(result);
                    PyArg_Parse(result, "d", &expressionResult.value);
                    if (fabs(expressionResult.value) < EPS_ZERO)
                        expressionResult.value = 0.0;
                    Py_DECREF(result);
                }
            }
        }

        if (returnValue)
            PyRun_String("del result_pythonlab", Py_single_input, m_dict, m_dict);
    }
    else
    {
        ScriptResult error = parseError();
        expressionResult.error = error.text;
        expressionResult.traceback = error.traceback;
    }
    Py_XDECREF(output);

    emit executedExpression();

    return expressionResult;
}
Exemple #7
0
QStringList PythonEngine::codeCompletion(const QString& command)
{
    QStringList out;

    runPythonHeader();

#pragma omp critical(completion)
    {
        PyObject *output = PyRun_String(command.toLatin1().data(), Py_single_input, m_dict, m_dict);

        // parse result
        if (output)
        {
            PyObject *result = PyDict_GetItemString(m_dict, "result_jedi_pythonlab");
            if (result)
            {
                Py_INCREF(result);
                PyObject *list;
                if (PyArg_Parse(result, "O", &list))
                {
                    int count = PyList_Size(list);
                    for (int i = 0; i < count; i++)
                    {
                        PyObject *item = PyList_GetItem(list, i);

                        QString str = PyString_AsString(item);

                        // remove builtin methods
                        if (!str.startsWith("__"))
                        {
                            //qDebug() << str;
                            out.append(str);
                        }
                    }
                }
                Py_DECREF(result);
            }

            PyObject *del = PyRun_String("del result_jedi_pythonlab", Py_single_input, m_dict, m_dict);
            Py_XDECREF(del);
        }
        else
        {
            PyErr_Clear();
        }

        Py_XDECREF(output);
    }

    return out;
}
Exemple #8
0
int interpreterGetConditionValue(Interpreter *interpreter, char *condition) {

	char* bufferCondition, *cval;
	int result;

	//PyEval_AcquireThread(interpreter->threadPythonState);

	PyEval_RestoreThread(interpreter->threadPythonState);

	bufferCondition = (char*)  malloc(sizeof(char) * 2048);

	memset(bufferCondition, 0, sizeof bufferCondition);

	sprintf(bufferCondition, "result = str(%s)", condition);

	PyRun_String(bufferCondition,
			Py_file_input,
			interpreter->pdict,
			interpreter->pdict);

	interpreter->pval = PyDict_GetItemString(interpreter->pdict, "result");

	PyArg_Parse(interpreter->pval, "s", &cval);

	result = (cval != NULL && strcmp("True", cval) == 0);

	free(bufferCondition);

	//PyEval_ReleaseThread(interpreter->threadPythonState) ;
	PyEval_SaveThread();

	return result;
}
GList *PyMySQLGetDatabaseList(const char *user, const char *password)
{
	PyObject *rs;

	if (PyMySQLConnect("", user, password) < 0)
		return NULL;

	rs = PyRun_String("PyUpdateCommandReturn(\"Show databases\")", Py_eval_input, pdict, pdict);
	if (rs)
	{
		unsigned int i;
		GList *glist = NULL;
		RowSet* list = ConvertPythonToRowset(rs);
		if (!list)
			return NULL;
		for (i = 0; i < list->rows; i++)
			glist = g_list_append(glist, g_strdup(list->data[i][0]));
		FreeRowset(list);
		return glist;
	}
	else
	{
		PyErr_Print();
		return NULL;
	}
}
static int PySQLiteConnect(const char *dbfilename, const char *user, const char *password)
{
	PyObject *con;
	char *name, *filename, *buf;
	int exists;

	name = g_strdup_printf("%s.db", dbfilename);
	filename = g_build_filename (szHomeDirectory, name, NULL);
	exists = g_file_test(filename, G_FILE_TEST_EXISTS);
	buf = g_strdup_printf("PySQLiteConnect(r'%s')", filename);

	/* Connect to database*/
	con = PyRun_String(buf, Py_eval_input, pdict, pdict);
	g_free(name);
	g_free(filename);
	g_free(buf);
	if (con == NULL)
	{
		PyErr_Print();
		return -1;
	}
	else if (con == Py_None)
	{
		outputl( _("Error connecting to database") );
		return -1;
	}
	if (!exists)
	{	/* Empty database file created - create tables */
		return 0;
	}
	else
		return 1;
}
Exemple #11
0
// eval the first parameter, return the value of the variable passed as second parameter
// for example you eval "x = 2" and want the value of x, you do pynerl:eval("x = 2", "x")
static ERL_NIF_TERM pynerl_eval(ErlNifEnv* env, int argc, const ERL_NIF_TERM argv[]) {
	Py_Initialize();
	char buff[BUFF_SIZE];

	PyObject *pResult=NULL, *pdict, *pval;
	ERL_NIF_TERM eResult;

	// TODO: error checking
	enif_get_string(env, argv[0], buff, BUFF_SIZE, ERL_NIF_LATIN1);

	pdict = PyDict_New();
    PyDict_SetItemString(pdict, "__builtins__", PyEval_GetBuiltins());

    pResult = PyRun_String(buff, Py_file_input, pdict, pdict);

	if (pResult == NULL) {
		eResult = pynerl_make_error(env, "exception", "Exception while running eval");
	}
	else {
		enif_get_string(env, argv[1], buff, BUFF_SIZE, ERL_NIF_LATIN1);
		pval = PyDict_GetItemString(pdict, buff);
		eResult = pynerl_obj_to_term(env, pval);
		Py_DECREF(pResult);
	}

	Py_DECREF(pdict);

	Py_Finalize();

	return eResult;
}
main() {
    /* run strings with low-level calls */
    char *cstr;
    PyObject *pstr, *pmod, *pdict;               /* with error tests */
    Py_Initialize();

    /* result = string.upper('spam') + '!' */
    pmod = PyImport_ImportModule("string");      /* fetch module */
    if (pmod == NULL)                            /* for name-space */
        error("Can't import module");

    pdict = PyModule_GetDict(pmod);              /* string.__dict__ */
    Py_DECREF(pmod);
    if (pdict == NULL)
        error("Can't get module dict");

    pstr = PyRun_String("upper('spam') + '!'", Py_eval_input, pdict, pdict);
    if (pstr == NULL)
        error("Error while running string");

    /* convert result to C */
    if (!PyArg_Parse(pstr, "s", &cstr))
        error("Bad result type");
    printf("%s\n", cstr);
    Py_DECREF(pstr);        /* free exported objects, not pdict */
}
Exemple #13
0
int PEVENT_PLUGIN_LOADER(struct pevent *pevent)
{
	PyObject *globals, *m, *py_pevent, *str, *res;

	Py_Initialize();

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

	res = PyRun_String(pypath, Py_file_input, globals, globals);
	if (!res) {
		PyErr_Print();
		return -1;
	} else
		Py_DECREF(res);

	str = PyString_FromString("pevent");
	if (!str)
		return -ENOMEM;

	py_pevent = PyLong_FromUnsignedLong((unsigned long)pevent);
	if (!py_pevent)
		return -ENOMEM;

	if (PyDict_SetItem(globals, str, py_pevent))
		fprintf(stderr, "failed to insert pevent\n");

	Py_DECREF(py_pevent);
	Py_DECREF(str);

	trace_util_load_plugins(pevent, ".py", load_plugin, globals);

	return 0;
}
Exemple #14
0
static void load_plugin(struct pevent *pevent, const char *path,
			const char *name, void *data)
{
	PyObject *globals = data;
	int len = strlen(path) + strlen(name) + 2;
	int nlen = strlen(name) + 1;
	char *full = malloc(len);
	char *n = malloc(nlen);
	char *load;
	PyObject *res;

	if (!full || !n)
		return;

	strcpy(full, path);
	strcat(full, "/");
	strcat(full, name);

	strcpy(n, name);
	n[nlen - 4] = '\0';

	asprintf(&load, pyload, full, n);
	if (!load)
		return;

	res = PyRun_String(load, Py_file_input, globals, globals);
	if (!res) {
		fprintf(stderr, "failed loading %s\n", full);
		PyErr_Print();
	} else
		Py_DECREF(res);

	free(load);
}
Exemple #15
0
bool LoadInitialModules(PyVis* pyVis) {
    std::string scriptName("EmbeddedBinding");
    std::string scriptNameShorthand("eb");
    if(!pyVis->LoadModule(scriptName)) {
        return false;
    }
    PyErr_Print();

    // So far this seems to be necessary to use EmbeddedBinding from the 
    // PyRun_SimpleString context, but they are still referencing the same module
    std::string importToSimple = std::string("import ") + scriptName; 
    PyRun_SimpleString(importToSimple.c_str()); 
    // Same, but now even more convenient! So like "eb.ScriptStep()"
    std::string importToSimpleShorthand = std::string("import ") + scriptName
        + std::string(" as ") + scriptNameShorthand;
    PyRun_SimpleString(importToSimpleShorthand.c_str());
    
    PyRun_SimpleString("import numpy"); // handy, was already loaded above anyway

    PyObject* scriptDict = pyVis->GetDict(scriptName);
    PyRun_String("ScriptCreate()", Py_eval_input, pyVis->consoleGlobalContextDict, scriptDict);
    pyVis->consoleLocalContextDict = scriptDict;

    PyObject* scriptStep = PyDict_GetItemString(scriptDict, "ScriptStep"); // borrowed ref
    pyVis->scriptStep = scriptStep;  // borrowed ref
    if(!scriptStep || !PyCallable_Check(scriptStep)) {
        printf("Error loading python potential step function linkage: no ScriptStep()\n");
        PyErr_Print();
        return false; 
    }

    return true;
}
bool EventListener::Compile()
{
	Rocket::Core::String function_name(64, "Event_%x", this);
	Rocket::Core::String function_code(64, "def %s():", function_name.CString());

	Rocket::Core::StringList lines;
	Rocket::Core::StringUtilities::ExpandString(lines, source_code, ';');
	for (size_t i = 0; i < lines.size(); i++)
	{
		// Python doesn't handle \r's, strip em and indent the code correctly
		function_code += Rocket::Core::String(1024, "\n\t%s", lines[i].CString()).Replace("\r", "");
	}

	ROCKET_ASSERT(element != NULL);

	PyObject* py_namespace = GetGlobalNamespace();

	// Add our function to the namespace
	PyObject* result = PyRun_String(function_code.CString(), Py_file_input, py_namespace, py_namespace);
	if (!result)
	{
		Rocket::Core::Python::Utilities::PrintError();		
		return false;
	}
	Py_DECREF(result);

	// Get a handle to our function
	callable = PyDict_GetItemString(py_namespace, function_name.CString());
	Py_INCREF(callable);

	return true;
}
Exemple #17
0
void OutputHook::call(std::string name, boost::python::object obj)
{
    Hooks::checkName(name);

    auto repr_ = PyObject_Repr(obj.ptr());
    if (PyErr_Occurred())
    {
        PyErr_Clear();
        throw Hooks::Exception("Failed to get __repr__ of argument");
    }
    auto repr = std::string(PyUnicode_AsUTF8(repr_));
    Py_DECREF(repr_);

    PyObject* g = Py_BuildValue(
            "{sO}", "__builtins__", PyEval_GetBuiltins());
    node->parent->loadDatumHooks(g);
    auto out = PyRun_String(repr.c_str(), Py_eval_input, g, g);
    Py_DECREF(g);
    Py_XDECREF(out);
    if (PyErr_Occurred())
    {
        PyErr_Clear();
        throw Hooks::Exception("Could not evaluate __repr__ of output");
    }

    const bool result = node->makeDatum(
            name, obj.ptr()->ob_type, Datum::SIGIL_OUTPUT + repr, true);

    if (!result)
        throw Hooks::Exception("Datum was already defined in this script.");
}
PyObject* getFileData(int argc, char *argv[])
{
    PyObject *BioModule = PyImport_ImportModule("Bio");
    const char *filename, *filetype, *pycmdToRun;
    filename = (const char *)PyUnicode_DecodeFSDefault(argv[1]);
    filetype = (const char *)PyUnicode_DecodeFSDefault(argv[2]);
    std::string cmdToRun = "import Bio\nBio.SeqIO.parse(";
    cmdToRun = cmdToRun + filename + std::string(",") + filetype;
    pycmdToRun = cmdToRun.c_str();

    wchar_t *program = Py_DecodeLocale(argv[0], NULL);
    if (program == NULL) {
        fprintf(stderr, "Fatal error: cannot decode argv[0]\n");
        exit(1);
    }
    
    Py_SetProgramName(program);  /* optional but recommended */
    Py_Initialize();
    PyObject* filedata;
    filedata = PyRun_String(pycmdToRun, 0, NULL, NULL);
    Py_DECREF(filename);
    Py_DECREF(filetype);
    Py_Finalize();
    PyMem_RawFree(program);

    return filedata;
}
Exemple #19
0
	PyObject* runSingleString_(const String& str, int mode)
	{
		// clear previous errors
		PyErr_Clear();
		error_message_ = "";
		
		// run the string through the interpreter
		PyObject* result = PyRun_String(const_cast<char*>(str.c_str()), mode, context_, context_);
		if (PyErr_Occurred())
		{
			PyObject* type;
			PyObject* value;
			PyObject* range;

			char* message;
			error_message_ = "ERROR: ";
			PyErr_Fetch(&type, &value, &range);
			if (PyArg_Parse(value, "s", &message))
			{
				error_message_ += message;
			}
			else
			{	
				error_message_ += " (error message could not be parsed)";
			}

			PyErr_Print();

			error_message_ += "\n";

			return 0;
		}
		
		return result;
	}
Exemple #20
0
std::string evalForString(const char * stmt,bool * ok = nullptr)
{
	if (ok != 0) *ok = false;
	PyObject* result = 0;
	run ([stmt,&result]()
	{

		PyObject* main = PyImport_AddModule("__main__");
		if (main == 0)
		{
			return;
		}
		PyObject* globalDictionary = PyModule_GetDict(main);
		if (globalDictionary == 0)
		{
			return ;
		}
		PyObject* localDictionary = PyDict_New();
		if (localDictionary == 0)
		{
			return ;
		}
		result = PyRun_String(stmt, Py_file_input, globalDictionary, localDictionary);
	});
	if (result == 0)
		return "";
	bool lok = false;
	std::string ret = convert<std::string>(result,ok?*ok:lok);
	Py_DecRef(result);
	return ret;
}
Exemple #21
0
int
PP_Run_Codestr(PPStringModes mode, const char *code,  /* expr or stmt string */
               const char *modname,                   /* loads module if needed */
               const char *resfmt, void *cresult)     /* converts expr result to C */
{
    /* run a string of Python code */
    int parse_mode;                             /* "eval(code, d, d)", or */
    PyObject *module, *dict, *presult;          /* "exec code in d, d" */

    module = PP_Load_Module(modname);           /* get module, init python */
    if (module == NULL)                         /* not incref'd */
        return -1;
    dict = PyModule_GetDict(module);            /* get dict namespace */
    if (dict == NULL)                           /* not incref'd */
        return -1;

    parse_mode = (mode == PP_EXPRESSION ? Py_eval_input : Py_file_input);
    if (PP_DEBUG) 
        presult = PP_Debug_Codestr(mode, code, dict);         /* run in pdb */
    else 
        presult = PyRun_String(code, parse_mode, dict, dict); /* eval direct */
                                                              /* increfs res */
    if (mode == PP_STATEMENT) {
        int result = (presult == NULL? -1 : 0);          /* stmt: 'None' */
        Py_XDECREF(presult);                             /* ignore result */
        return result;
    }
    return PP_Convert_Result(presult, resfmt, cresult);  /* expr val to C */
}
Exemple #22
0
PyMODINIT_FUNC
PYENTRY_FUNC_NAME(void)
{
    PyObject *module = NULL;
#ifdef PY3K
    module = PyModule_Create(&wsql_module);
#else
    module = Py_InitModule3(#MODULE_NAME, wsql_methods, wsql__doc__);
#endif
    if (!module)
        PY_MOD_RETURN(NULL); /* this really should never happen */

    /* Populate final object settings */
    if (PyType_Ready(&wsql_connection_t) < 0) goto on_error;
    if (PyType_Ready(&wsql_result_t) < 0) goto on_error;
    if (PyType_Ready(&wsql_field_t) < 0) goto on_error;

    /* Module constants */
    if (PyModule_AddObject(module, "version_info",
                           PyRun_String(STRINGIFY(MODULE_VERSION_INFO),
                                        Py_eval_input,
                                        PyModule_GetDict(module),
                                        PyModule_GetDict(module))) < 0) goto on_error;

    if (PyModule_AddStringConstant(module, "__version__", STRINGIFY(MODULE_VERSION)) < 0) goto on_error;

    if (wsql_exceptions_init(module) < 0) goto on_error;
    if (wsql_constants_init(module) < 0) goto on_error;

    PY_MOD_RETURN(module);

  on_error:
    Py_XDECREF(module);
    PY_MOD_RETURN(NULL);
}
RowSet *PySelect(const char* str)
{
	PyObject *rs;
	char *buf = g_strdup_printf("PySelect(\"%s\")", str);
	/* Remove any new lines from query string */
	char *ppch = buf;
	while (*ppch)
	{
      if (strchr( "\t\n\r\v\f", *ppch ) )
		  *ppch = ' ';
	  ppch++;
	}

	/* Run select */
	rs = PyRun_String(buf, Py_eval_input, pdict, pdict);
	g_free(buf);

	if (rs)
	{
		return ConvertPythonToRowset(rs);
	}
	else
	{
		PyErr_Print();
		return NULL;
	}
}
Exemple #24
0
__declspec(dllexport) __stdcall char * _ExPyEval(const char *cmd, int stoken)
{
  PyGILState_STATE state;
  PyObject *m=NULL, *d=NULL;
  check_init();
  state = PyGILState_Ensure();

  m = PyImport_ImportModule("__main__");

  if (m) d = PyModule_GetDict(m);

  if (d) {
    PyObject *res = PyRun_String(cmd, 
				 stoken,
				 d, d);
    if (! res)
    {
      PyErr_Print();
    }
    char *rres=PyString_AsString(PyObject_Str(res));
    /* Note that the count of the PyObject_Str object is not
       decremented here*/
    Py_XDECREF(res);
    Py_XDECREF(m);
    return rres;
  } 
  else 
  {
    SystemError(1, "could not import __main__");
  }
  return NULL;
}
Exemple #25
0
void SceneDeserializer::deserializeDatum(QJsonObject in, Node* node, Info* info)
{
    // Lazy initialization of globals dictionary
    static PyObject* globals = NULL;
    if (!globals)
    {
        globals = Py_BuildValue("{sO}", "__builtins__", PyEval_GetBuiltins());
        PyDict_SetItemString(globals, "_fabtypes",
                             PyImport_ImportModule("_fabtypes"));
    }

    // Evaluate the type string in the Python interpreter,
    // getting a type object out.
    auto t = PyRun_String(
                  in["type"].toString().toStdString().c_str(),
                  Py_eval_input, globals, globals);
    Q_ASSERT(t);
    Q_ASSERT(PyType_Check(t));

    auto datum = new Datum(in["name"].toString().toStdString(),
                           in["uid"].toDouble(),
                           in["expr"].toString().toStdString(),
                           (PyTypeObject*)t, node);

    if (info && in.contains("subdatum"))
    {
        auto i = in["subdatum"].toArray();
        info->frames.subdatum[datum] = QPointF(i[0].toDouble(), i[1].toDouble());
    }
}
Exemple #26
0
void init_interpreter(void)
{
	PyObject *code_executed;

#ifdef READLINE
    rl_initialize();
    (char*(*)(const char*, int))rl_completion_entry_function = (char*(*)(const char*, int))rl_python_completion_function;
#endif

    Py_Initialize();
    
    interpreter_state = (InterpreterState *)malloc(sizeof(InterpreterState));
    
    // Get the main dictionary
    interpreter_state->main_module  = PyImport_AddModule("__main__");
    interpreter_state->main_dict    = PyModule_GetDict(
                                        interpreter_state->main_module);
    
    code_executed = PyRun_String(
        interpreter_initialization_code, Py_file_input,
        interpreter_state->main_dict, NULL);
    interpreter_state->capture_stdout = PyMapping_GetItemString(
        interpreter_state->main_dict, "capture_stdout");
    interpreter_state->capture_stderr = PyMapping_GetItemString(
        interpreter_state->main_dict, "capture_stderr");
                
    Py_DECREF(code_executed);
    
    return;
}
Exemple #27
0
void PythonEngine::deleteUserModules()
{
    // delete all user modules
    //
    // When working with Python scripts interactively, one must keep in mind that Python
    // import a module from its source code (on disk) only when parsing the first corresponding
    // import statement. During this first import, the byte code is generated (.pyc file)
    // if necessary and the imported module code object is cached in sys.modules. Then, when
    // re-importing the same module, this cached code object will be directly used even
    // if the source code file (.py[w] file) has changed meanwhile.
    //
    // This behavior is sometimes unexpected when working with the Python interpreter in
    // interactive mode, because one must either always restart the interpreter or remove manually the .pyc
    // files to be sure that changes made in imported modules were taken into account.

    QStringList filter_name;
    filter_name << "pythonlab" << "agros2d" << "sys";

    QList<PythonVariable> list = variableList();

    foreach (PythonVariable variable, list)
    {
        if (variable.type == "module")
        {
            if (filter_name.contains(variable.name))
                continue;

            QString exp = QString("del %1; del sys.modules[\"%1\"]").arg(variable.name);
            // qDebug() << exp;
            PyRun_String(exp.toLatin1().data(), Py_single_input, m_dict, m_dict);
        }
    }

    PyErr_Clear();
}
void configParserStruct::pythonParser::runString( const std::string &Program )
{
  std::string PrefixString;
  for ( std::map<std::string,std::string>::const_iterator i = ExternalVariables.begin(); i != ExternalVariables.end(); ++i )
    PrefixString += i->first + " = " + i->second + "\n";

  PyRun_String( ( PrefixString + Program ).c_str(), Py_file_input, castToPyObject(Dictionary), castToPyObject(Dictionary) );
}
Exemple #29
0
object BOOST_PYTHON_DECL exec(str string, object global, object local)
{
  // should be 'char const *' but older python versions don't use 'const' yet.
  char *s = python::extract<char *>(string);
  PyObject* result = PyRun_String(s, Py_file_input, global.ptr(), local.ptr());
  if (!result) throw_error_already_set();
  return object(detail::new_reference(result));
}
python::object LocalPythonInterpreter::execsingle(python::str code)
{
	setupLocalNamespaceBindings();
	char *s = python::extract<char *>(code);
	PyObject* result = PyRun_String(s, Py_single_input, m_globalNamespace.ptr(), m_localNamespace.ptr());
	if (!result) python::throw_error_already_set();
	return python::object(python::detail::new_reference(result));
}