bool PythonScript::exec()
{
    if (isFunction) compiled = notCompiled;
    if (compiled != Script::isCompiled && !compile(false))
        return false;
    PyObject *pyret;
    beginStdoutRedirect();
    if (PyCallable_Check(PyCode)) {
        PyObject *empty_tuple = PyTuple_New(0);
        if (!empty_tuple) {
            emit_error(env()->errorMsg(), 0);
            return false;
        }
        pyret = PyObject_Call(PyCode,empty_tuple,localDict);
        Py_DECREF(empty_tuple);
    } else {
        pyret = PyEval_EvalCode((PyCodeObject*)PyCode, env()->globalDict(), localDict);
        //pyret = PyRun_String(Code, 0, env()->globalDict(), localDict);
    }

    endStdoutRedirect();
    if (pyret) {
        Py_DECREF(pyret);
        return true;
    }
    emit_error(env()->errorMsg(), 0);
    return false;
}
Exemple #2
0
PyObject *
PyImport_ExecCodeModule(char *name, PyObject *co)
{
    LOG("> PyImport_ExecCodeModule\n");
    {

        PyObject *m, *d, *v;

        m = PyImport_AddModule(name);

        if (m == NULL)
            return NULL;
        d = PyModule_GetDict(m);

        if (PyDict_GetItemString(d, "__builtins__") == NULL) {
            if (PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins()) != 0) {
                return NULL;
            }
        }

        v = PyEval_EvalCode((PyCodeObject *)co, d, d);

        if (v == NULL)
            return NULL;
        Py_DECREF(v);

        LOG("< PyImport_ExecCodeModule\n");
        return m;
    }
}
Exemple #3
0
void PyRun::trigger(const Eref& e, double input)
{
    if (!runcompiled_){
        return;
    }
    if (mode_ == 1){
        return;
    }
    
    PyObject * value = PyDict_GetItemString(locals_, inputvar_.c_str());
    if (value){
        Py_DECREF(value);
    }
    value = PyFloat_FromDouble(input);
    if (!value && PyErr_Occurred()){
        PyErr_Print();
    }
    if (PyDict_SetItemString(locals_, inputvar_.c_str(), value)){
        PyErr_Print();
    }
    PyEval_EvalCode(runcompiled_, globals_, locals_);
    if (PyErr_Occurred()){
        PyErr_Print ();
    }
    value = PyDict_GetItemString(locals_, outputvar_.c_str());
    if (value){
        double output = PyFloat_AsDouble(value);
        if (PyErr_Occurred()){
            PyErr_Print ();
        } else {
            outputOut()->send(e, output);
        }
    }
}
Exemple #4
0
/**
 * Add a Python variable of the workspace name
 * to the current scope
 * @param wsName The name of the workspace
 * @param ws The ws ptr (unused)
 */
void PythonScript::addPythonReference(const std::string& wsName,const Mantid::API::Workspace_sptr ws)
{
    UNUSED_ARG(ws);

    // Compile a code object
    const size_t length = wsName.length() * 2 + 10;
    char * code = new char[length + 1];
    const char * name = wsName.c_str();
    sprintf(code, "%s = mtd['%s']", name, name);
    PyObject *codeObj = Py_CompileString(code, "PythonScript::addPythonReference", Py_file_input);
    if( codeObj )
    {
        PyObject *ret = PyEval_EvalCode((PyCodeObject*)codeObj,localDict, localDict);
        Py_XDECREF(ret);
    }
    if( PyErr_Occurred() )
    {
        PyErr_Clear();
    }
    else
    {
        // Keep track of it
        m_workspaceHandles.insert(m_workspaceHandles.end(), wsName);
    }
    Py_XDECREF(codeObj);
    delete [] code;
}
void run_code(PyObject *code, PyObject *dict, const char *locale) {
  if(script_loop_depth >= MAX_LOOP_DEPTH) {
    // should we flag some sort of error, here?
    //***********
    // FINISH ME
    //***********

    script_ok = FALSE;
  }
  else {
    listPush(locale_stack, strdupsafe(locale));

    // try executing the code
    script_ok = TRUE;
    script_loop_depth++;
    PyObject *retval = PyEval_EvalCode((PyCodeObject *)code, dict, dict);
    script_loop_depth--;

    // did we throw an error?
    if(retval == NULL && PyErr_Occurred() != PyExc_SystemExit)
      script_ok = FALSE;

    // garbage collection
    free(listPop(locale_stack));
    Py_XDECREF(retval);
  }
}
Exemple #6
0
static void cmd_exec(const char *data)
{
    PyObject *co;
    PyObject *ret;
    PyObject *d;
    PyObject *m;
    char *cmd;

    if (!*data)
        cmd_return_error(CMDERR_NOT_ENOUGH_PARAMS);

    cmd = g_strconcat(data, "\n", NULL);
    
    m = PyImport_AddModule("__main__");
    if (!m)
        goto error;

    d = PyModule_GetDict(m);
    if (!d)
        goto error;

    co = Py_CompileString(cmd, "<stdin>", Py_single_input);
    if (!co)
        goto error;

    ret = PyEval_EvalCode((PyCodeObject *)co, d, d);
    Py_DECREF(co);
    Py_XDECREF(ret);

error:
    g_free(cmd);
    if (PyErr_Occurred())
        PyErr_Print();
}
FB::variant PyHelloWorldAPI::hello_py()
{
    PyObject* src = Py_CompileString("result = 'hello js!'", "hello_world.py", Py_single_input);

    std::string result_str;

    if (src != 0)                         /* compiled just fine - */
    {
        PyObject* locals = PyDict_New ();

        PyObject* py_eval;
        PyObject* py_result;
        py_eval = PyEval_EvalCode((PyCodeObject *)src, globals, locals); 

        PyObject* res_key = PyString_FromString("result");
        py_result = PyDict_GetItem(locals, res_key);

        PyObject* py_str = PyObject_Str(py_result);

        result_str = __convert_py_to_string(py_str);

        Py_XDECREF(py_str);
        Py_XDECREF(py_eval);

        // crashes... don't know why this is not legal
        //Py_XDECREF(locals);

    } else  {
        result_str = "Compilation of python src failed.";
    }

    FB::variant result(result_str);

    return result;
}
static PyObject *
run_pyc_file(FILE *fp, char *filename, PyObject *globals, PyObject *locals)
{
	PyCodeObject *co;
	PyObject *v;
	long magic;
	long PyImport_GetMagicNumber(void);

	magic = PyMarshal_ReadLongFromFile(fp);
	if (magic != PyImport_GetMagicNumber()) {
		PyErr_SetString(PyExc_RuntimeError,
			   "Bad magic number in .pyc file");
		return NULL;
	}
	(void) PyMarshal_ReadLongFromFile(fp);
	v = PyMarshal_ReadObjectFromFile(fp);
	fclose(fp);
	if (v == NULL || !PyCode_Check(v)) {
		Py_XDECREF(v);
		PyErr_SetString(PyExc_RuntimeError,
			   "Bad code object in .pyc file");
		return NULL;
	}
	co = (PyCodeObject *)v;
	v = PyEval_EvalCode(co, globals, locals);
	Py_DECREF(co);
	return v;
}
Exemple #9
0
int run_script(void)
{
	int rc = 0;

	/* load the code objects to execute */
	PyObject *m=NULL, *d=NULL, *seq=NULL;
	/* We execute then in the context of '__main__' */
	m = PyImport_AddModule("__main__");
	if (m) d = PyModule_GetDict(m);
	if (d) seq = PyMarshal_ReadObjectFromString(pScript, numScriptBytes);
	if (seq) {
		Py_ssize_t i, max = PySequence_Length(seq);
		for (i=0;i<max;i++) {
			PyObject *sub = PySequence_GetItem(seq, i);
			if (sub /*&& PyCode_Check(sub) */) {
				PyObject *discard = PyEval_EvalCode((PyCodeObject *)sub,
									d, d);
				if (!discard) {
					PyErr_Print();
					rc = 255;
				}
				Py_XDECREF(discard);
				/* keep going even if we fail */
			}
			Py_XDECREF(sub);
		}
	}
	return rc;
}
Exemple #10
0
static PyObject* runPythonFile(FILE* fp, char* pathname) {
	
	PyCodeObject *co = parse_source_module(pathname, fp);
	if (co == NULL)
		return NULL;

	//PyObject *m = PyImport_ExecCodeModuleEx("<pyinjected module>", (PyObject *)co, pathname);
    
	PyObject *globals = PyDict_New();
	
	if (PyDict_SetItemString(globals, "__builtins__",
							 PyEval_GetBuiltins()) != 0)
		return NULL;
	
	if (PyDict_SetItemString(globals, "__file__",
							 PyString_FromString(pathname)) != 0)
		return NULL;

	PyObject* v = PyEval_EvalCode((PyObject *)co, globals, globals);
	
	Py_DECREF(globals);
	Py_DECREF(co);
	
	//return m;
	return v;
}
Exemple #11
0
//-----------------------------------------------------------------------------
// ExecuteScript()
//   Execute the script found within the file.
//-----------------------------------------------------------------------------
static int ExecuteScript(
    const char *fileName)               // name of file containing Python code
{
    PyObject *importer, *dict, *code, *temp;

    if (SetExecutableName(fileName) < 0)
        return -1;
    if (SetPathToSearch() < 0)
        return -1;
    importer = NULL;
    if (GetImporter(&importer) < 0)
        return -1;

    // create and populate dictionary for initscript module
    dict = PyDict_New();
    if (PopulateInitScriptDict(dict) < 0) {
        Py_XDECREF(dict);
        Py_DECREF(importer);
        return -1;
    }

    // locate and execute script
    code = PyObject_CallMethod(importer, "get_code", "s", "cx_Freeze__init__");
    Py_DECREF(importer);
    if (!code)
        return FatalError("unable to locate initialization module");
    temp = PyEval_EvalCode( (EvalCodeType*) code, dict, dict);
    Py_DECREF(code);
    Py_DECREF(dict);
    if (!temp)
        return FatalScriptError();
    Py_DECREF(temp);

    return 0;
}
Exemple #12
0
void mat_eval_compiled_code(PyObject *code_obj, int parse_mode)
{
	PyObject *code_executed;

    DEBUG("eval_code: running PyEval_EvalCode")
    
    // Evaluate the code.
    code_executed = (PyObject *)PyEval_EvalCode(
        (PyCodeObject *)code_obj,
        interpreter_state->main_dict,
        interpreter_state->main_dict);
        
    if(!code_executed) {
        DEBUG("eval_code: PyEval_EvalCode failed")
        handle_error();
        return;
    }
    DEBUG("eval_code: code executed")
    
    DEBUG("eval_code: showing output")
    
    
    if(parse_mode==Py_eval_input) {
    
        // If the mode is Py_eval_input and the code evaluated
        // successfully, an expression has been executed and the
        // resulting value is the returned Python object.
        // The interpreter will output a string representation of
        // the object.
        DEBUG("eval_code: showing repr")
        
        python_to_mathematica_object(code_executed);
        
        // Mathematica can only receive in one stream (no separate way of
        // feeding stderr/stdour messages). If an object is returned, then
        // any text printed, which would be otherwise returned as a string,
        // is discarded.
        flush_std(interpreter_state->capture_stdout);
        
        // Free unneeded object.
        Py_DECREF(code_executed);
        return;
        
    } else {
    
        // Otherwise, the code evaluated was one or more statements
        // which do not return a value, if any output has been
        // produced, it will be available in the Capture instance
        // The output is shown by the interpreter.
        DEBUG("eval_code: showing stdout")
        process_std(interpreter_state->capture_stdout);
        return;
    }
    
    
    MLPutSymbol(stdlink, "Null");
    
    return;
}
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;
}
main() {
    int i;
    char *cval;
    PyObject *pcode1, *pcode2, *pcode3, *presult, *pdict;
    char *codestr1, *codestr2, *codestr3;
    printf("embed-bytecode\n");

    Py_Initialize();
    codestr1 = "import usermod\nprint usermod.message";     /* statements */
    codestr2 = "usermod.transform(usermod.message)";        /* expression */
    codestr3 = "print '%d:%d' % (X, X ** 2),";              /* use input X */

    /* make new namespace dictionary */
    pdict = PyDict_New();
    if (pdict == NULL) return -1;
    PyDict_SetItemString(pdict, "__builtins__", PyEval_GetBuiltins());
 
    /* precompile strings of code to bytecode objects */
    pcode1 = Py_CompileString(codestr1, "<embed>", Py_file_input); 
    pcode2 = Py_CompileString(codestr2, "<embed>", Py_eval_input); 
    pcode3 = Py_CompileString(codestr3, "<embed>", Py_file_input); 

    /* run compiled bytecode in namespace dict */
    if (pcode1 && pcode2 && pcode3) {
        (void)    PyEval_EvalCode((PyCodeObject *)pcode1, pdict, pdict);
        presult = PyEval_EvalCode((PyCodeObject *)pcode2, pdict, pdict);
        PyArg_Parse(presult, "s", &cval); 
        printf("%s\n", cval);            
        Py_DECREF(presult);

        /* rerun code object repeatedly */
        for (i = 0; i <= 10; i++) {
            PyDict_SetItemString(pdict, "X", PyInt_FromLong(i)); 
            (void) PyEval_EvalCode((PyCodeObject *)pcode3, pdict, pdict);
        }
        printf("\n");
    }

    /* free referenced objects */
    Py_XDECREF(pdict);
    Py_XDECREF(pcode1);
    Py_XDECREF(pcode2);
    Py_XDECREF(pcode3);
}
Exemple #15
0
/**
 * Executes the compiled code object. If NULL nothing happens
 * @param compiledCode An object that has been compiled from a code fragment
 * @return The result python object
 */
PyObject* PythonScript::executeCompiledCode(PyObject *compiledCode)
{
    PyObject *result(NULL);
    if(!compiledCode) return result;

    InstallTrace traceInstall(*this);
    beginStdoutRedirect();
    result = PyEval_EvalCode((PyCodeObject*)compiledCode, localDict, localDict);
    endStdoutRedirect();
    return result;
}
Exemple #16
0
void PyRun::reinit(const Eref& e, ProcPtr p)
{
    PyObject * main_module;
    if (globals_ == NULL){
        main_module = PyImport_AddModule("__main__");        
        globals_ = PyModule_GetDict(main_module);
        Py_XINCREF(globals_);
    }
    if (locals_ == NULL){
        locals_ = PyDict_New();
        if (!locals_){
            cerr << "Could not initialize locals dict" << endl;            
        }
    }
    initcompiled_ = (PyCodeObject*)Py_CompileString(
        initstr_.c_str(),
        Py_GetProgramName(),
        Py_file_input);
    if (!initcompiled_){
        cerr << "Error compiling initString" << endl;
        handleError(true);
    } else {
        PyEval_EvalCode(initcompiled_, globals_, locals_);
        if (PyErr_Occurred()){
            PyErr_Print ();
        }
    }
    runcompiled_ = (PyCodeObject*)Py_CompileString(
        runstr_.c_str(),
        Py_GetProgramName(),
        Py_file_input);
    if (!runcompiled_){
        cerr << "Error compiling runString" << endl;
        handleError(true);
    } else {
        PyEval_EvalCode(runcompiled_, globals_, locals_);
        if (PyErr_Occurred()){
            PyErr_Print ();
        }
    }
}
 /// The normal PyRun_String method does not allow a filename to
 /// be passed along for better error messages and trace backs.
 /// This function does the same as PyRun_String but 
 /// also takes the filename where the string originated from.
 inline PyObject *PyRun_StringFilename( const char *str, 
                                        const char *filename,
                                        int start, 
                                        PyObject *globals, 
                                        PyObject *locals) {
   PyCodeObject *co = (PyCodeObject *)Py_CompileString(str, filename, start);
   if (co == NULL)
     return NULL;
   PyObject *v = PyEval_EvalCode(co, globals, locals);
   Py_DECREF(co);
   return v;
 }
Exemple #18
0
/* execute Python code, propagate Python errors to the backend */
static PyObject *
PLy_procedure_call(PLyProcedure *proc, const char *kargs, PyObject *vargs)
{
	PyObject   *rv;
	int volatile save_subxact_level = list_length(explicit_subtransactions);

	PyDict_SetItemString(proc->globals, kargs, vargs);

	PG_TRY();
	{
#if PY_VERSION_HEX >= 0x03020000
		rv = PyEval_EvalCode(proc->code,
							 proc->globals, proc->globals);
#else
		rv = PyEval_EvalCode((PyCodeObject *) proc->code,
							 proc->globals, proc->globals);
#endif

		/*
		 * Since plpy will only let you close subtransactions that you
		 * started, you cannot *unnest* subtransactions, only *nest* them
		 * without closing.
		 */
		Assert(list_length(explicit_subtransactions) >= save_subxact_level);
	}
	PG_CATCH();
	{
		PLy_abort_open_subtransactions(save_subxact_level);
		PG_RE_THROW();
	}
	PG_END_TRY();

	PLy_abort_open_subtransactions(save_subxact_level);

	/* If the Python code returned an error, propagate it */
	if (rv == NULL)
		PLy_elog(ERROR, NULL);

	return rv;
}
Exemple #19
0
static PyObject*
create_module(char *name, PyObject *co)
{
	PyObject *m;
	PyObject *d;
	PyObject *v;
	PyObject *err;
	assert(name);
	assert(co);
	/*创建一个新的模块*/
	m = PyModule_New(name);
	if(m == NULL)
	{
		Ps_Log("create new module failed\n", Ps_LOG_WARING);
		return NULL;
	}
	/*初始化这个新的模块*/
	d = PyModule_GetDict(m);
	if(PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins()) != 0)
	{
		Ps_Log("Set new module builtin failed\n", Ps_LOG_WARING);
		PyErr_SetString(PyExc_ImportError, "Cannot get builtin dict");
		goto error;
	}
	v= ((PyCodeObject*)co)->co_filename;
	Py_INCREF(v);
	if(PyDict_SetItemString(d, "__file__", v) != 0)
		PyErr_Clear();
	Py_DECREF(v);
#ifdef IMPORT_DEBUG
	Ps_Log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n", Ps_LOG_NORMAL);
	//Ps_LogObject(d, Ps_LOG_NORMAL);
	Ps_Log("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$\n", Ps_LOG_NORMAL);
#endif

	/*执行字节码*/
	v = PyEval_EvalCode((PyCodeObject*)co, d, d);
	if(v == NULL || (err = PyErr_Occurred()))
	{
		Ps_LogObject(d, Ps_LOG_WARING);
		Ps_Log("PyEval_EvalCode failed\n", Ps_LOG_WARING);
		return NULL;
		//goto error;
	}
	Py_XDECREF(v);

	Py_INCREF(m);
	return m;
error:
	Py_DECREF(m);
	return NULL;
}
static PyObject *
run_node(node *n, char *filename, PyObject *globals, PyObject *locals)
{
	PyCodeObject *co;
	PyObject *v;
	co = PyNode_Compile(n, filename);
	PyNode_Free(n);
	if (co == NULL)
		return NULL;
	v = PyEval_EvalCode(co, globals, locals);
	Py_DECREF(co);
	return v;
}
static PyObject *
run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
	 PyCompilerFlags *flags, PyArena *arena)
{
	PyCodeObject *co;
	PyObject *v;
	co = PyAST_Compile(mod, filename, flags, arena);
	if (co == NULL)
		return NULL;
	v = PyEval_EvalCode(co, globals, locals);
	Py_DECREF(co);
	return v;
}
Exemple #22
0
static PyObject *
run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
	 PyCompilerFlags *flags, PyArena *arena)
{
	STACKLESS_GETARG();
	PyCodeObject *co;
	PyObject *v;
	co = PyAST_Compile(mod, filename, flags, arena);
	if (co == NULL)
		return NULL;
	STACKLESS_PROMOTE_ALL();
	v = PyEval_EvalCode(co, globals, locals);
	STACKLESS_ASSERT();
	Py_DECREF(co);
	return v;
}
//! evaluates code, using argDict (borrowed reference) as local dictionary or an empty one if argDict==NULL
//! name is the filename Python uses when reporting errors
//! returns a new reference; NULL means caller has to do exception handling
PyObject *PythonScripting::eval(const QString &code, PyObject *argDict, const char *name)
{
  PyObject *args;
  if (argDict)
  {
    Py_INCREF(argDict);
    args = argDict;
  } else
    args = PyDict_New();
  PyObject *ret=NULL;
  PyObject *co = Py_CompileString(code.ascii(), name, Py_eval_input);
  if (co)
  {
    ret = PyEval_EvalCode((PyCodeObject*)co, globals, args);
    Py_DECREF(co);
  }
  Py_DECREF(args);
  return ret;
}
Exemple #24
0
ScriptResult PythonEngine::runPythonScript(const QString &script, const QString &fileName)
{
    m_isRunning = true;
    m_stdOut = "";

    QSettings settings;
    // enable user module deleter
    if (settings.value("PythonEngine/UserModuleDeleter", true).toBool())
        deleteUserModules();

    runPythonHeader();

    PyObject *output = NULL;
    if (QFile::exists(fileName))
    {
        QString str = QString("from os import chdir; chdir(u'" + QFileInfo(fileName).absolutePath() + "')");
        PyRun_String(str.toStdString().c_str(), Py_single_input, m_dict, m_dict);
    }
    // compile
    PyObject *code = Py_CompileString(script.toStdString().c_str(), fileName.toStdString().c_str(), Py_file_input);
    // run
    if (code) output = PyEval_EvalCode((PyCodeObject *) code, m_dict, m_dict);

    ScriptResult scriptResult;
    if (output)
    {
        scriptResult.isError = false;
        scriptResult.text = m_stdOut.trimmed();
    }
    else
    {
        scriptResult = parseError();
    }
    Py_XDECREF(output);

    m_isRunning = false;

    emit executedScript();

    return scriptResult;
}
//! executes code, using argDict (borrowed reference) as local dictionary or an empty one if argDict==NULL
//! name is the filename Python uses when reporting errors
//! a false return value means caller has to do exception handling
bool PythonScripting::exec (const QString &code, PyObject *argDict, const char *name)
{
  PyObject *args;
  if (argDict)
  {
    Py_INCREF(argDict);
    args = argDict;
  } else
    args = PyDict_New();
  PyObject *tmp = NULL;
  PyObject *co = Py_CompileString(code.ascii(), name, Py_file_input);
  if (co)
  {
    tmp = PyEval_EvalCode((PyCodeObject*)co, globals, args);
    Py_DECREF(co);
  }
  Py_DECREF(args);
  if (!tmp) return false;
  Py_DECREF(tmp);
  return true;
}
Exemple #26
0
static PyObject *
run_eval_code_obj(PyCodeObject *co, PyObject *globals, PyObject *locals)
{
    PyObject *v;
    /*
     * We explicitly re-initialize _Py_UnhandledKeyboardInterrupt every eval
     * _just in case_ someone is calling into an embedded Python where they
     * don't care about an uncaught KeyboardInterrupt exception (why didn't they
     * leave config.install_signal_handlers set to 0?!?) but then later call
     * Py_Main() itself (which _checks_ this flag and dies with a signal after
     * its interpreter exits).  We don't want a previous embedded interpreter's
     * uncaught exception to trigger an unexplained signal exit from a future
     * Py_Main() based one.
     */
    _Py_UnhandledKeyboardInterrupt = 0;
    v = PyEval_EvalCode((PyObject*)co, globals, locals);
    if (!v && PyErr_Occurred() == PyExc_KeyboardInterrupt) {
        _Py_UnhandledKeyboardInterrupt = 1;
    }
    return v;
}
Exemple #27
0
int
PP_Run_Bytecode(PyObject *codeobj,           /* run compiled bytecode object */
                const char     *modname,           /* in named module's namespace */
                const char     *resfmt, void *restarget)
{
    PyObject *presult, *module, *dict;

    if (! PyCode_Check(codeobj))             /* make sure it's bytecode */
        return -1;
    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;
    if (PP_DEBUG)
        presult = PP_Debug_Bytecode(codeobj, dict);        /* run in pdb */
    else
        presult = PyEval_EvalCode((PyCodeObject *)codeobj, dict, dict);
    return PP_Convert_Result(presult, resfmt, restarget);  /* expr val to C */
}
Exemple #28
0
void PyRun::process(const Eref & e, ProcPtr p)
{
    // PyRun_String(runstr_.c_str(), 0, globals_, locals_);
    // PyRun_SimpleString(runstr_.c_str());
    if (!runcompiled_ || mode_ == 2){
        return;
    }
    PyEval_EvalCode(runcompiled_, globals_, locals_);
    if (PyErr_Occurred()){
        PyErr_Print ();
    }
    PyObject * value = PyDict_GetItemString(locals_, outputvar_.c_str());
    if (value){
        double output = PyFloat_AsDouble(value);
        if (PyErr_Occurred()){
            PyErr_Print ();
        } else {
            outputOut()->send(e, output);
        }
    }
}
    virtual void fire()
    {
        boost::python::handle<> aHandle(
            PyEval_EvalCode(
                reinterpret_cast< PyCodeObject* >( theCompiledExpression.get() ),
                theGlobalNamespace.ptr(), theLocalNamespace.ptr() ) );

        boost::python::object aResultObject( aHandle );
        
        // do not use extract<double> for efficiency
        if( ! PyFloat_Check( aResultObject.ptr() ) )
        {
            THROW_EXCEPTION_INSIDE( SimulationError, 
                             asString() + ": "
                             "The expression gave a non-float object." );
        }

        const Real aFlux( PyFloat_AS_DOUBLE( aResultObject.ptr() ) );

        setFlux( aFlux );
    }
    bool PythonScript::run(bool outputInfo) {
        if (isCompileNeeded_ && !compile(outputInfo)) {
            LogError("Failed to run script, script could not be compiled");
            return false;
        }

        ivwAssert(byteCode_ != nullptr, "No byte code");

        if (outputInfo) LogInfo("Running compiled script ...");
       
        auto m = PyImport_AddModule("__main__");
        if (m == NULL) return false;
       
        auto d = PyModule_GetDict(m);

        PyObject* copy = PyDict_Copy(d);
        PyObject* ret = PyEval_EvalCode(BYTE_CODE, copy, copy);
        bool success = checkRuntimeError();
        Py_XDECREF(ret);
        Py_XDECREF(copy);
        return success;
    }