00001 /* 00002 * PythonExecuter.cpp 00003 * 00004 * Created on: Oct 28, 2013 00005 * Author: blackpc 00006 */ 00007 00008 #include <scriptable_monitor/PythonExecuter.h> 00009 00010 PyThreadState* PythonExecuter::_mainState = NULL; 00011 set<string> PythonExecuter::_initializedModules; 00012 00013 void PythonExecuter::initialize() 00014 { 00015 if (Py_IsInitialized()) 00016 return; 00017 00018 int argc = 1; 00019 char* argv[] = { "python_executer" }; 00020 PyEval_InitThreads(); 00021 Py_InitializeEx(0); 00022 PyObject *pModule = PyImport_AddModule("__main__"); 00023 PySys_SetArgv(argc, argv); 00024 _mainState = PyEval_SaveThread(); 00025 } 00026 00027 void PythonExecuter::finalize() 00028 { 00029 if (!Py_IsInitialized()) 00030 return; 00031 00032 PyEval_RestoreThread(_mainState); 00033 Py_Finalize(); 00034 } 00035 00036 void PythonExecuter::initModule(string name, PyMethodDef* methodDef) 00037 { 00038 if (!Py_IsInitialized()) 00039 initialize(); 00040 00041 if (_initializedModules.count(name) > 0) { 00042 cout << "Module '" << name << "' already added to python environment" << endl; 00043 return; 00044 } 00045 00046 _initializedModules.insert(name); 00047 00048 PyEval_RestoreThread(_mainState); 00049 Py_InitModule(name.c_str(), methodDef); 00050 _mainState = PyEval_SaveThread(); 00051 00052 cout << "Module '" << name << "' successfully added to python environment" << endl; 00053 } 00054 00055 void PythonExecuter::execute(string code) 00056 { 00057 if (!Py_IsInitialized()) 00058 initialize(); 00059 00060 PyGILState_STATE state = PyGILState_Ensure(); 00061 PyRun_SimpleString(code.c_str()); 00062 PyGILState_Release(state); 00063 } 00064 00065 CompilationResult PythonExecuter::compile(string code) 00066 { 00067 if (!Py_IsInitialized()) 00068 initialize(); 00069 00070 PyGILState_STATE state = PyGILState_Ensure(); 00071 00072 CompilationResult result; 00073 PyObject* codeObject = Py_CompileString(code.c_str(), "", Py_file_input); 00074 result.success = codeObject != NULL; 00075 00076 PyGILState_Release(state); 00077 00078 return result; 00079 }