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;
}
Пример #2
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;
}
Пример #3
0
/**
 * @param code A lump of python code
 * @return True if the code forms a complete statment
 */
bool PythonScript::compilesToCompleteStatement(const QString & code) const
{
    bool result(false);
    GlobalInterpreterLock gil;
    PyObject *compiledCode = Py_CompileString(code.toAscii(), "", Py_file_input);
    if( PyObject *exception = PyErr_Occurred() )
    {
        // Certain exceptions still mean the code is complete
        if(PyErr_GivenExceptionMatches(exception, PyExc_SyntaxError) ||
                PyErr_GivenExceptionMatches(exception, PyExc_OverflowError) ||
                PyErr_GivenExceptionMatches(exception, PyExc_ValueError) ||
                PyErr_GivenExceptionMatches(exception, PyExc_TypeError) ||
                PyErr_GivenExceptionMatches(exception, PyExc_MemoryError))
        {
            result = true;
        }
        else
        {
            result = false;
        }
        PyErr_Clear();
    }
    else
    {
        result = true;
    }
    Py_XDECREF(compiledCode);
    return result;
}
Пример #4
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();
}
Пример #5
0
PyObject *bpy_text_import(Text *text)
{
	char *buf = NULL;
	char modulename[MAX_ID_NAME + 2];
	int len;

	if (!text->compiled) {
		char fn_dummy[256];
		bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);

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

		if (PyErr_Occurred()) {
			PyErr_Print();
			PyErr_Clear();
			PySys_SetObject("last_traceback", NULL);
			free_compiled_text(text);
			return NULL;
		}
	}

	len = strlen(text->id.name + 2);
	BLI_strncpy(modulename, text->id.name + 2, len);
	modulename[len - 3] = '\0'; /* remove .py */
	return PyImport_ExecCodeModule(modulename, text->compiled);
}
Пример #6
0
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;
}
Пример #7
0
PyObject* PyTempleImporter::LoadModule(PyObject* self, PyObject* args) {

	char *fullname;
	if (!PyArg_ParseTuple(args, "s:PyTempleImporter.LoadModule", &fullname))
		return nullptr;

	auto moduleInfo = instance->GetModuleInfo(fullname);
	if (!moduleInfo.found) {
		// If it was found before, why not now?
		return nullptr;
	}

	// Try loading compiled code first
	if (moduleInfo.sourcePath.empty()) {
		throw TempleException("Bytecode not supported yet");
	}
	auto data = ReadData(moduleInfo.sourcePath);
	auto code = Py_CompileString(PyString_AsString(data), moduleInfo.sourcePath.c_str(), Py_file_input);

	if (!code) {
		return nullptr; // Compilation error
	}

	auto module = PyImport_AddModule(fullname);	
	if (!module) {
		Py_DECREF(code);
		return nullptr;
	}

	auto moduleDict = PyModule_GetDict(module);
	if (PyDict_SetItemString(moduleDict, "__loader__", self) != 0) {
		Py_DECREF(code);
		Py_DECREF(module);
		return nullptr;
	}

	if (moduleInfo.package) {
		PyObject *packagePath = PyString_FromString(moduleInfo.packagePath.c_str());
		PyObject *packagePathList = Py_BuildValue("[O]", packagePath);
		Py_DECREF(packagePath);
		if (!packagePathList) {
			Py_DECREF(code);
			Py_DECREF(module);
			return nullptr;
		}
		auto err = PyDict_SetItemString(moduleDict, "__path__", packagePathList);
		Py_DECREF(packagePathList);
		if (err != 0) {
			Py_DECREF(code);
			Py_DECREF(module);
			return nullptr;
		}
	}

	module = PyImport_ExecCodeModuleEx(fullname, code, const_cast<char*>(moduleInfo.sourcePath.c_str()));
	Py_DECREF(code);
	
	return module;
}
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);
}
Пример #9
0
void Py(char *input) {
    PyObject *code_obj;

    clean_input(input);
    
    // Compile the user input as an expression.  
    code_obj = Py_CompileString(input, "User Input", Py_eval_input);
    
    if(code_obj) {
    
        // If the compilation was successful, the resulting code
        // object is evaluated.
        DEBUG("execute_input: evaluating eval_input")
        
        mat_eval_compiled_code(code_obj, Py_eval_input);
        Py_DECREF(code_obj);
        
        return;
        
    } else {
    
        DEBUG("execute_input: evaluating file_input")
        
        // If the compilation did not succeed probably the
        // code was not an expression. Subsequently it will now
        // be compiled as a statement or group of statements.
        // The error is therefore cleared. If it triggers again
        // after this compilation then there will be a syntax
        // or other kind or error in the user's input.
        PyErr_Clear();
        
        code_obj = Py_CompileString(input, "User Input", Py_file_input);
        if(code_obj) {
            mat_eval_compiled_code(code_obj, Py_file_input);
            Py_DECREF(code_obj);
        
            return;
        }
	}
			
    handle_error();
	return;
}
Пример #10
0
PyObject *bpy_text_reimport(PyObject *module, int *found)
{
	Text *text;
	const char *name;
	char *filepath;
	char *buf = NULL;
//XXX	Main *maggie = bpy_import_main ? bpy_import_main:G.main;
	Main *maggie = bpy_import_main;
	
	if (!maggie) {
		printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
		return NULL;
	}
	
	*found = 0;
	
	/* get name, filename from the module itself */
	if ((name = PyModule_GetName(module)) == NULL)
		return NULL;

	if ((filepath = (char *)PyModule_GetFilename(module)) == NULL)
		return NULL;

	/* look up the text object */
	text = BLI_findstring(&maggie->text, BLI_path_basename(filepath), offsetof(ID, name) + 2);

	/* uh-oh.... didn't find it */
	if (!text)
		return NULL;
	else
		*found = 1;

	/* if previously compiled, free the object */
	/* (can't see how could be NULL, but check just in case) */ 
	if (text->compiled) {
		Py_DECREF((PyObject *)text->compiled);
	}

	/* compile the buffer */
	buf = txt_to_buf(text);
	text->compiled = Py_CompileString(buf, text->id.name + 2, Py_file_input);
	MEM_freeN(buf);

	/* if compile failed.... return this error */
	if (PyErr_Occurred()) {
		PyErr_Print();
		PyErr_Clear();
		PySys_SetObject("last_traceback", NULL);
		free_compiled_text(text);
		return NULL;
	}

	/* make into a module */
	return PyImport_ExecCodeModule((char *)name, text->compiled);
}
Пример #11
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 ();
        }
    }
}
Пример #12
0
 /// 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;
 }
Пример #13
0
PyPyCondition::PyPyCondition(const string& arg) {
  PYLOCK;
  py_func = Py_CompileString(arg.c_str(), ("<mod_py condition: '"+arg+"'>").c_str(), Py_eval_input);
  if (NULL == py_func) {
    ERROR("compiling python code '%s'\n", 
	  arg.c_str());
    if(PyErr_Occurred())
      PyErr_Print();

    throw string("compiling python code '" + arg +"'");
  }
}
Пример #14
0
/* Given a string buffer containing Python source code, compile it
   return and return a code object as a new reference. */
static PyObject *
compile_source(char *pathname, PyObject *source)
{
    PyObject *code, *fixed_source;

    fixed_source = normalize_line_endings(source);
    if (fixed_source == NULL)
        return NULL;

    code = Py_CompileString(PyString_AsString(fixed_source), pathname,
                            Py_file_input);
    Py_DECREF(fixed_source);
    return code;
}
Пример #15
0
/*
 * Insert the procedure into the Python interpreter
 */
void
PLy_procedure_compile(PLyProcedure *proc, const char *src)
{
	PyObject   *crv = NULL;
	char	   *msrc;

	proc->globals = PyDict_Copy(PLy_interp_globals);

	/*
	 * SD is private preserved data between calls. GD is global data shared by
	 * all functions
	 */
	proc->statics = PyDict_New();
	if (!proc->statics)
		PLy_elog(ERROR, NULL);
	PyDict_SetItemString(proc->globals, "SD", proc->statics);

	/*
	 * insert the function code into the interpreter
	 */
	msrc = PLy_procedure_munge_source(proc->pyname, src);
	/* Save the mangled source for later inclusion in tracebacks */
	proc->src = MemoryContextStrdup(proc->mcxt, msrc);
	crv = PyRun_String(msrc, Py_file_input, proc->globals, NULL);
	pfree(msrc);

	if (crv != NULL)
	{
		int			clen;
		char		call[NAMEDATALEN + 256];

		Py_DECREF(crv);

		/*
		 * compile a call to the function
		 */
		clen = snprintf(call, sizeof(call), "%s()", proc->pyname);
		if (clen < 0 || clen >= sizeof(call))
			elog(ERROR, "string would overflow buffer");
		proc->code = Py_CompileString(call, "<string>", Py_eval_input);
		if (proc->code != NULL)
			return;
	}

	if (proc->proname)
		PLy_elog(ERROR, "could not compile PL/Python function \"%s\"",
				 proc->proname);
	else
		PLy_elog(ERROR, "could not compile anonymous PL/Python code block");
}
Пример #16
0
const bool PythonScript::import()
{
	// Opens the script's source file.
	std::string source;
	bool result = vgio::readFile(m_filename.string(), source);
	if( !result )
	{
		qDebug() << "Error opening file: " << m_filename.c_str();
		QMessageBox::information(0, "Script loading error", QString());
		return false;
	}	
	
	// Compiles the code from the given python source file and create the associated module.
	PyObject * code = 0;
	code = Py_CompileString( source.c_str(), m_filename.string().c_str(), Py_file_input );
	if( !code )
	{
		PyErr_Print();
		QMessageBox::warning( 0, "Script error", "An error has occured while load the script. Please see the console for additional details." );
		return false;
	}
	m_pyModule = PyImport_ExecCodeModule( "script", code ) ;
	Py_DECREF(code);

	// References the module of the script module in the __main___ module for later use.
	PyObject * mainModule = PyImport_AddModule("__main__");
	PyObject * mainDict = PyModule_GetDict(mainModule);
	PyDict_SetItemString(mainDict, "script", m_pyModule);

    // Adds . in sys.path on posix platform
#ifndef WIN32
    std::string path = Py_GetPath();
    path = ":" + path;
    PySys_SetPath( path.c_str() );
#endif

	// Import vgsdk libraries 
	PyObject * scriptDict = PyModule_GetDict(m_pyModule);
	PyObject * vgdModule = PyImport_ImportModule("vgd");
	PyDict_SetItemString(scriptDict, "vgd", vgdModule);
	PyObject * vgmModule = PyImport_ImportModule("vgm");
	PyDict_SetItemString(scriptDict, "vgm", vgmModule);
	PyObject * vgeModule = PyImport_ImportModule("vge");
	PyDict_SetItemString(scriptDict, "vge", vgeModule);
	PyObject * vgUIModule = PyImport_ImportModule("vgUI");
	PyDict_SetItemString(scriptDict, "vgUI", vgUIModule);

	// Job's done.
	return true;
}
Пример #17
0
    bool PythonScript::compile(bool outputInfo) {
        if (outputInfo)
            LogInfo("Compiling script");

        Py_XDECREF(BYTE_CODE);
        byteCode_ = Py_CompileString(source_.c_str(), filename_.c_str(), Py_file_input);
        isCompileNeeded_ = !checkCompileError();

        if (isCompileNeeded_) {
            Py_XDECREF(BYTE_CODE);
            byteCode_ = nullptr;
        }

        return !isCompileNeeded_;
    }
Пример #18
0
PyObject *
PP_Compile_Codestr(PPStringModes mode,    /* precompile string to bytecode */
                   const char *codestr)         /* pass result to PP_Run_Bytecode */
{
    int start;
    Py_Initialize();
    switch (mode) {
    case PP_STATEMENT:
        start = Py_file_input; break;
    case PP_EXPRESSION:
        start = Py_eval_input; break;
    default:
        start = Py_single_input;  /* prints expr results */
    }
    return Py_CompileString(codestr, "<PP_Compile_Codestr>", start);
}
Пример #19
0
PyObject *run_script_forcode(PyObject *dict, const char *script, 
			     const char *locale) {
  // try compiling the code
  PyObject *retval = Py_CompileString(script, "<string>", Py_file_input);

  // try running the code
  if(retval != NULL)
    run_code(retval, dict, locale);
  
  // did we end up with an error?
  if(retval == NULL || !last_script_ok())
    log_pyerr("Script terminated with an error:\r\n%s", script);

  // return our code object
  return retval;
}
Пример #20
0
bool PythonInterpreter::compileScript(const char* code) {
    PyEval_RestoreThread(state);

    PyObject* ans = Py_CompileString(const_cast<char*>(code), "<script>",
        Py_file_input);
    if (ans) {
        Py_DECREF(ans);
        state = PyEval_SaveThread();
        return true;
    } else {
        PyErr_Print();
        PyErr_Clear();
        state = PyEval_SaveThread();
        return false;
    }
}
Пример #21
0
QString
QPythonPriv::importFromQRC(const char *module, const QString &filename)
{
    PyObject *sys_modules = PySys_GetObject((char *)"modules");
    if (!PyMapping_Check(sys_modules)) {
        return QString("sys.modules is not a mapping object");
    }

    PyObject *qrc_importer = PyMapping_GetItemString(sys_modules,
            (char *)module);

    if (qrc_importer == NULL) {
        PyErr_Clear();

        QFile qrc_importer_code(":" + filename);
        if (!qrc_importer_code.open(QIODevice::ReadOnly)) {
            return QString("Cannot load qrc importer source");
        }

        QByteArray ba = qrc_importer_code.readAll();
        QByteArray fn = QString("qrc:/" + filename).toUtf8();

        PyObject *co = Py_CompileString(ba.constData(), fn.constData(),
                Py_file_input);
        if (co == NULL) {
            QString result = QString("Cannot compile qrc importer: %1")
                .arg(formatExc());
            PyErr_Clear();
            return result;
        }

        qrc_importer = PyImport_ExecCodeModule((char *)module, co);
        if (qrc_importer == NULL) {
            QString result = QString("Cannot exec qrc importer: %1")
                    .arg(formatExc());
            PyErr_Clear();
            return result;
        }
        Py_XDECREF(co);
    }

    Py_XDECREF(qrc_importer);

    return QString();
}
//! 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;
}
Пример #23
0
int uwsgi_request_eval(struct wsgi_request *wsgi_req) {
	PyObject *code, *py_dict;

	UWSGI_GET_GIL
		PyObject *m = PyImport_AddModule("__main__");
	if (m == NULL) {
		PyErr_Print();
		return -1;
	}

	py_dict = PyModule_GetDict(m);
	// make it a valid c string
	wsgi_req->buffer[wsgi_req->uh.pktsize] = 0;
	// need to find a way to cache compilations...
	code = Py_CompileString(wsgi_req->buffer, "uWSGI", Py_file_input);
	if (code == NULL) {
		PyErr_Print();
		UWSGI_RELEASE_GIL
			return -1;
	}
Пример #24
0
bool SCA_PythonController::Compile()
{
	m_bModified= false;
	
	// if a script already exists, decref it before replace the pointer to a new script
	if (m_bytecode) {
		Py_DECREF(m_bytecode);
		m_bytecode=NULL;
	}
	
	// recompile the scripttext into bytecode
	m_bytecode = Py_CompileString(m_scriptText.c_str(), m_scriptName.c_str(), Py_file_input);
	
	if (m_bytecode) {
		return true;
	} else {
		ErrorPrint("Python error compiling script");
		return false;
	}
}
Пример #25
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;
}
Пример #27
0
/* Given a string buffer containing Python source code, compile it
   return and return a code object as a new reference. */
static PyObject *
compile_source(PyObject *pathname, PyObject *source)
{
    PyObject *code, *fixed_source, *pathbytes;

    pathbytes = PyUnicode_EncodeFSDefault(pathname);
    if (pathbytes == NULL)
        return NULL;

    fixed_source = normalize_line_endings(source);
    if (fixed_source == NULL) {
        Py_DECREF(pathbytes);
        return NULL;
    }

    code = Py_CompileString(PyBytes_AsString(fixed_source),
                            PyBytes_AsString(pathbytes),
                            Py_file_input);
    Py_DECREF(pathbytes);
    Py_DECREF(fixed_source);
    return code;
}
PyCodeObject *CompilePython (const std::string &name) {
  Python::reseterrors();
  PyCodeObject * retval = compiled_python.Get (name);
  Python::reseterrors();
  if (retval) {
    return retval;
  }
  char * str  = LoadString (name.c_str());
  if (str) {
    fprintf(stdout,"Compiling python module %s\n",name.c_str());

    std::string compiling_name = getCompilingName(name).c_str();
    char * temp = strdup(compiling_name.c_str());

    retval = (PyCodeObject *) Py_CompileString (str,temp,Py_file_input);
    if (retval) {
      compiled_python.Put(name,retval);
    }
    free (temp);
    free (str);
  }
  return retval;
}
Пример #29
0
/**
 * Delete a Python reference to the given workspace name
 * @param wsName The name of the workspace
 */
void PythonScript::deletePythonReference(const std::string& wsName)
{
    const size_t length = wsName.length() + 4;
    char * code = new char[length + 1];
    sprintf(code, "del %s", wsName.c_str());
    PyObject *codeObj = Py_CompileString(code, "PythonScript::deleteHandle", Py_file_input);
    if( codeObj )
    {
        PyObject *ret = PyEval_EvalCode((PyCodeObject*)codeObj,localDict, localDict);
        Py_XDECREF(ret);
    }
    if( PyErr_Occurred() )
    {
        PyErr_Clear();
    }
    else
    {
        m_workspaceHandles.erase(wsName);
    }
    Py_XDECREF(codeObj);
    delete [] code;

}
Пример #30
0
//! Checks CSL script for errors.
int
py_compile(const char *script_path)
{
    /*!
     * Checks CSL script for errors.
     *
     * @script_path Absolute or relative path of the CSL script.
     * @return 0 on success, 1 on IO errors (missing file, etc.), 2 on script error
     */

    PyObject *pCode;
    char *code = load_file(script_path, NULL);
    if (!code) {
        return 1;
    }

    pCode = Py_CompileString(code, "<script.py>", Py_file_input);
    free(code);
    if (!pCode) {
        return 2;
    }

    return 0;
}