本文整理汇总了C++中PyRun_String函数的典型用法代码示例。如果您正苦于以下问题:C++ PyRun_String函数的具体用法?C++ PyRun_String怎么用?C++ PyRun_String使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyRun_String函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: ERROR_MSG
//-------------------------------------------------------------------------------------
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;
}
示例2: python_eval
/**
@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;
}
示例3: connect
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);
}
示例4: QString
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;
}
示例5: PyDict_SetItemString
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;
}
示例6: runPythonHeader
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;
}
示例7: runPythonHeader
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;
}
示例8: interpreterGetConditionValue
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;
}
示例9: PyRun_String
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;
}
}
示例10: PySQLiteConnect
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;
}
示例11: pynerl_eval
// 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;
}
示例12: main
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 */
}
示例13: PEVENT_PLUGIN_LOADER
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;
}
示例14: load_plugin
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);
}
示例15: LoadInitialModules
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;
}