int ExecFile(char *FileName) { PyObject* PyFileObject = PyFile_FromString(FileName, "r"); if (!PyFileObject) { return 0; } if (PyRun_SimpleFile(PyFile_AsFile(PyFileObject), FileName) == 0) { Py_DECREF(PyFileObject); return 1; } else { Py_DECREF(PyFileObject); return 0; } }
static void python_run_simple_file (FILE *file, const char *filename) { #ifndef _WIN32 PyRun_SimpleFile (file, filename); #else /* _WIN32 */ char *full_path; PyObject *python_file; struct cleanup *cleanup; /* Because we have a string for a filename, and are using Python to open the file, we need to expand any tilde in the path first. */ full_path = tilde_expand (filename); cleanup = make_cleanup (xfree, full_path); python_file = PyFile_FromString (full_path, "r"); if (! python_file) { do_cleanups (cleanup); gdbpy_print_stack (); error (_("Error while opening file: %s"), full_path); } make_cleanup_py_decref (python_file); PyRun_SimpleFile (PyFile_AsFile (python_file), filename); do_cleanups (cleanup); #endif /* _WIN32 */ }
/* Loads a file into a module; it is not inserted into sys.modules */ static int py_load_module(PyObject *module, const char *path) { PyObject *dict, *ret, *fp; if (PyModule_AddStringConstant(module, "__file__", (char *)path) < 0) return 0; dict = PyModule_GetDict(module); if (PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins()) < 0) return 0; /* Dont use the standard library to avoid incompatabilities with the FILE structure and Python */ fp = PyFile_FromString((char *)path, "r"); if (!fp) return 0; ret = PyRun_File(PyFile_AsFile(fp), path, Py_file_input, dict, dict); Py_DECREF(fp); /* XXX: I assume that the file is closed when refs drop to zero? */ if (!ret) return 0; Py_DECREF(ret); return 1; }
Pyramid::Pyramid(const char* script) { freopen("pyramid.log", "w", stdout); freopen("pyramid.log", "a", stderr); Py_SetProgramName(".\\pyramid"); Py_Initialize(); init_pyramid(); PyRun_SimpleString( "import sys\n" "sys.path.append('./')\n" "sys.stderr = open('python_errors.log', 'w', 0)\n" "sys.stdout = open('pyramid.log', 'a', 0)\n" "import pyramid\n"); char* fn_local = new char[strlen(script)+1]; strcpy(fn_local, script); PyObject* fp = PyFile_FromString(fn_local, "r"); if(!fp) { printf("Could not load mapping script '%s' for reading.\n", script); Py_Finalize(); exit(1); } FILE* sfp = PyFile_AsFile(fp); PyRun_AnyFileEx(sfp, script, 1); delete[] fn_local; }
static foreign_t python_run_file(term_t file) { char *s; size_t len; char si[256]; s = si; if (PL_get_nchars(file, &len, &s, CVT_ALL | CVT_EXCEPTION)) { #if PY_MAJOR_VERSION < 3 PyObject *PyFileObject = PyFile_FromString(si, "r"); PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), "test.py", 1); #else FILE *f = fopen(s, "r"); if (f == NULL) { return false; } PyRun_SimpleFileEx(f, s, 1); #endif { { return true; } } } { return false; } }
int main(int argc, char *argv[]) { // Set the python interpreter. setup_python(argc, argv); std::string filepath(argv[0]); // Get the path to the helper script. std::string helper_path; size_t path_end = filepath.find_last_of('\\'); if (path_end != std::string::npos) helper_path = filepath.substr(0, path_end + 1); helper_path += "wbadminhelper.py"; // Configures the execution of the script to take the same // parameters as this helper tool. Py_SetProgramName(argv[0]); PySys_SetArgv(argc, argv); // Executes the helper script. PyObject *pFileObject = PyFile_FromString(const_cast<char *>(helper_path.c_str()), "r"); PyRun_SimpleFileEx(PyFile_AsFile(pFileObject), "wbadminhelper.py", 1); finalize_python(); return 0; }
bool PythonInterpreter::runScript(const char* filename, const char* shortName) { PyEval_RestoreThread(state); PyObject* script = PyFile_FromString(const_cast<char*>(filename), const_cast<char*>("r")); if (script) { PyObject* ans = PyRun_File(PyFile_AsFile(script), const_cast<char*>(shortName), Py_file_input, mainNamespace, mainNamespace); Py_DECREF(script); if (ans) { Py_DECREF(ans); state = PyEval_SaveThread(); return true; } else { PyErr_Print(); state = PyEval_SaveThread(); return false; } } else { state = PyEval_SaveThread(); return false; } }
// Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); #if PY_VERSION_HEX >= 0x03000000 // TODO(bhy) temporary workaround for Python 3. // should figure out a way to avoid binary incompatibilities as the Python 2 // version did. FILE *fs = fopen(f, "r"); #else // Let python open the file to avoid potential binary incompatibilities. PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r")); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); FILE *fs = PyFile_AsFile(file.get()); #endif PyObject* result = PyRun_File(fs, f, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); }
DSN_PY_API dsn_error_t dsn_app_bridge(int argc, const char** argv) { std::vector< std::string> args; for (int i = 0; i < argc; i++) { std::string ag(*argv++); args.push_back(ag); } new std::thread([=](){ Py_Initialize(); char* PyFileName = (char *)args[0].c_str(); char** PyParameterList = new char* [args.size()]; for (int i = 0;i < args.size(); ++i) { PyParameterList[i] = new char[args[i].size()+1]; strcpy(PyParameterList[i], args[i].c_str()); } PySys_SetArgv((int)args.size(), PyParameterList); PyObject* PyFileObject = PyFile_FromString(PyFileName, "r"); PyRun_SimpleFile(PyFile_AsFile(PyFileObject), PyFileName); Py_Finalize(); for (int i = 0; i < args.size(); ++i) { delete [] PyParameterList[i]; } delete [] PyParameterList; }); dsn_app_loader_wait(); return dsn::ERR_OK; }
// Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // Set suitable default values for global and local dicts. object none; if (global.ptr() == none.ptr()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.ptr() == none.ptr()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); // Let python open the file to avoid potential binary incompatibilities. PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r")); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); PyObject* result = PyRun_File(PyFile_AsFile(file.get()), f, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); }
static int igraphmodule_i_filehandle_init_pypy_2(igraphmodule_filehandle_t* handle, PyObject* object, char* mode) { int fp; PyObject* fpobj; char* fname; if (object == 0 || (!PyBaseString_Check(object) && !PyFile_Check(object))) { PyErr_SetString(PyExc_TypeError, "string or file handle expected"); return 1; } handle->need_close = 0; if (PyBaseString_Check(object)) { /* We have received a string; we need to open the file denoted by this * string now and mark that we opened the file ourselves (so we need * to close it when igraphmodule_filehandle_destroy is invoked). */ handle->object = PyFile_FromString(PyString_AsString(object), mode); if (handle->object == 0) { /* Could not open the file; just return an error code because an * exception was raised already */ return 1; } /* Remember that we need to close the file ourselves */ handle->need_close = 1; } else { /* This is probably a file-like object; store a reference for it and * we will handle it later */ handle->object = object; Py_INCREF(handle->object); } /* PyPy does not have PyFile_AsFile, so we will try to access the file * descriptor instead by calling its fileno() method and then opening the * file handle with fdopen */ fpobj = PyObject_CallMethod(handle->object, "fileno", 0); if (fpobj == 0 || !PyInt_Check(fpobj)) { if (fpobj != 0) { Py_DECREF(fpobj); } igraphmodule_filehandle_destroy(handle); /* This already called Py_DECREF(handle->object), no need to call it. * Also, an exception was raised by PyObject_CallMethod so no need to * raise one ourselves */ return 1; } fp = (int)PyInt_AsLong(fpobj); Py_DECREF(fpobj); handle->fp = fdopen(fp, mode); if (handle->fp == 0) { igraphmodule_filehandle_destroy(handle); /* This already called Py_DECREF(handle->object), no need to call it */ PyErr_SetString(PyExc_RuntimeError, "fdopen() failed unexpectedly"); return 1; } return 0; }
//-------------------------------------------------------------------------- void PyW_RunPyFile(const char *fn) { char *v_fn = qstrdup(fn); PyObject *py_fp = PyFile_FromString(v_fn, "r"); FILE *fp = PyFile_AsFile(py_fp); PyRun_SimpleFile(fp, v_fn); qfree(v_fn); }
/** * \ingroup python_interface_filehandle * \brief Constructs a new file handle object from a Python object. * * \return 0 if everything was OK, 1 otherwise. An appropriate Python * exception is raised in this case. */ int igraphmodule_filehandle_init(igraphmodule_filehandle_t* handle, PyObject* object, char* mode) { #ifdef IGRAPH_PYTHON3 int fp; if (object == 0 || PyLong_Check(object)) { PyErr_SetString(PyExc_TypeError, "string or file-like object expected"); return 1; } #else if (object == 0 || (!PyBaseString_Check(object) && !PyFile_Check(object))) { PyErr_SetString(PyExc_TypeError, "string or file handle expected"); return 1; } #endif if (PyBaseString_Check(object)) { #ifdef IGRAPH_PYTHON3 handle->object = PyFile_FromObject(object, mode); #else handle->object = PyFile_FromString(PyString_AsString(object), mode); #endif if (handle->object == 0) return 1; } else { handle->object = object; Py_INCREF(handle->object); } /* At this stage, handle->object is something we can handle. * In Python 2, we get here only if object is a file object. In * Python 3, object can be anything, and PyFile_FromObject will * complain if the object cannot be converted to a file handle. */ #ifdef IGRAPH_PYTHON3 fp = PyObject_AsFileDescriptor(handle->object); if (fp == -1) { Py_DECREF(handle->object); return 1; } handle->fp = fdopen(fp, mode); if (handle->fp == 0) { Py_DECREF(handle->object); PyErr_SetString(PyExc_RuntimeError, "fdopen() failed unexpectedly"); return 1; } #else handle->fp = PyFile_AsFile(handle->object); if (handle->fp == 0) { Py_DECREF(handle->object); PyErr_SetString(PyExc_RuntimeError, "PyFile_AsFile() failed unexpectedly"); return 1; } #endif return 0; }
int CPython::ExecFile(const std::vector<std::wstring> &argv, std::wstring &err, HANDLE hfile) { int id = 0; FILE *pfile = nullptr; DWORD count = 0; PyObject *poldout, *polderr, *pnewout, *pnewerr; if (argv.size() <= 0) { err = text("No python script file found"); return 1; } if (DuplicateHandle ( GetCurrentProcess(), hfile, GetCurrentProcess(), &hfile, 0, false, DUPLICATE_SAME_ACCESS )) { id = open_osfhandle((intptr_t)hfile, _O_WRONLY); pfile = fdopen(id,"w"); setvbuf(pfile,nullptr,_IONBF,1024); poldout = PySys_GetObject("stdout"); polderr = PySys_GetObject("stderr"); pnewout = PyFile_FromFile(pfile, "logger", "w", nullptr); pnewerr = PyFile_FromFile(pfile, "logger", "w", nullptr); PySys_SetObject("stdout", pnewout); PySys_SetObject("stderr", pnewerr); } else poldout = polderr = pnewout = pnewerr = nullptr; // Pack up the arguments .. std::vector<char*> args; int irslt = 0; std::vector<std::wstring>::const_iterator itr, eitr; std::wstring_convert<std::codecvt_utf8_utf16<wchar>> cvt; itr = argv.cbegin(); eitr = argv.cend(); for (size_t len = 0; itr != eitr; ++itr) { // Allocate buffer each time, not good .. std::string str = cvt.to_bytes(*itr); len = str.length(); char *arg = new char[len+1]; strncpy_s(arg,len+1,str.data(),len); arg[len] = '\0'; args.push_back(arg); } PySys_SetArgv(args.size(), args.data()); // pass args . PyObject *pobj = PyFile_FromString(args.at(0), "r"); if (pobj == nullptr) { err = text("Internal error that PyFile_FromString fail"); irslt = -1; } else { PyRun_SimpleFileEx(PyFile_AsFile(pobj), args.at(0), true); err = text("Execute python script file successfully .."); irslt = 00; } // Free resource ... std::vector<char*>::iterator sitr, seitr; sitr = args.begin(); seitr = args.end(); for (sitr; sitr != seitr; ++sitr) { if (*sitr) delete [] *sitr; } args.clear(); if (pnewout != nullptr) PySys_SetObject("stdout", poldout); if (pnewerr != nullptr) PySys_SetObject("stderr", polderr); if (pfile != nullptr) fclose(pfile); return irslt; }
// Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); // Let python open the file to avoid potential binary incompatibilities. PyObject *pyfile = PyFile_FromString(f, "r"); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); PyObject* result = PyRun_File(PyFile_AsFile(file.get()), f, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); }
int setup_virtualenv(){ // Setup the given virtualenv for python, if given if (PY_VIRTUAL_ENV!=NULL){ //char* cmd = "import os\nenv_path=u'"; //cmd = combine(cmd, PY_VIRTUAL_ENV); //cmd = combine(cmd, "'\nif os.path.exists(env_path):\n" // " execfile(u'%s/activate_this.py'%(env_path)," // " dict(__file__=u'%s/activate_this.py'%(env_path)))"); //PyRun_SimpleString(cmd); //PyRun_SimpleFile char* activateFile = combine(PY_VIRTUAL_ENV,"\\activate_this.py"); PyObject* PyFileObject = PyFile_FromString(activateFile, "r"); PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), activateFile, 1); } return 0; }
/*! Starts the python interpreter */ void startPython( int argc, char* argv[] ) { Py_SetProgramName( argv[0] ); Py_NoSiteFlag = 1; // No import because we need to set the search path first Py_Initialize(); PySys_SetArgv( argc, argv ); // Modify our search-path PyObject* searchpath = PySys_GetObject( "path" ); QStringList elements = QStringList::split( ";", Config::instance()->getString( "General", "Python Searchpath", "./scripts;.", true ) ); // Prepend our items to the searchpath for ( int i = elements.count() - 1; i >= 0; --i ) { PyList_Insert( searchpath, 0, PyString_FromString( elements[i].latin1() ) ); } // Import site now PyObject* m = PyImport_ImportModule( "site" ); Py_XDECREF( m ); // Try changing the stderr + stdout pointers PyObject* file = PyFile_FromString( "python.log", "w" ); if ( file ) { Py_INCREF( file ); PySys_SetObject( "stderr", file ); Py_INCREF( file ); PySys_SetObject( "stdout", file ); Py_DECREF( file ); } try { init_wolfpack_globals(); } catch ( ... ) { Console::instance()->send( "Failed to initialize the python extension modules\n" ); } }
static PyObject * flow_FlowLog(PyObject *self, PyObject *args, PyObject *kw_args) { FlowLogObject *rv; static char *keywords[] = { "path", "mode", NULL }; char *path = NULL, *mode = "rb"; if (!PyArg_ParseTupleAndKeywords(args, kw_args, "s|s:FlowLog", keywords, &path, &mode)) return NULL; if ((rv = PyObject_New(FlowLogObject, &FlowLog_Type)) == NULL) return (NULL); if ((rv->flowlog = PyFile_FromString(path, mode)) == NULL) return (NULL); PyFile_SetBufSize(rv->flowlog, 8192); return (PyObject *)rv; }
// Executed when script is called void execscript(char* scriptname) { Py_SetProgramName("optimsoc_cli"); Py_Initialize(); printf("\nExecute script %s.\n\n", scriptname); Py_InitModule("optimsoc", pythonMethods); PyObject* file = PyFile_FromString(scriptname, "r"); if (!file) { printf("Cannot find %s. Abort.\n",scriptname); return; } PyRun_SimpleString("from optimsoc import *"); PyRun_SimpleFileEx(PyFile_AsFile(file), scriptname, 1); }
static int igraphmodule_i_filehandle_init_cpython_2(igraphmodule_filehandle_t* handle, PyObject* object, char* mode) { if (object == 0 || (!PyBaseString_Check(object) && !PyFile_Check(object))) { PyErr_SetString(PyExc_TypeError, "string or file handle expected"); return 1; } handle->need_close = 0; if (PyBaseString_Check(object)) { /* We have received a string; we need to open the file denoted by this * string now and mark that we opened the file ourselves (so we need * to close it when igraphmodule_filehandle_destroy is invoked). */ handle->object = PyFile_FromString(PyString_AsString(object), mode); if (handle->object == 0) { /* Could not open the file; just return an error code because an * exception was raised already */ return 1; } /* Remember that we need to close the file ourselves */ handle->need_close = 1; } else { /* This is probably a file-like object; store a reference for it and * we will handle it later */ handle->object = object; Py_INCREF(handle->object); } /* At this stage, handle->object is something we can handle. * We get here only if object is a file object so we * can safely call PyFile_AsFile to get a FILE* object. */ handle->fp = PyFile_AsFile(handle->object); if (handle->fp == 0) { igraphmodule_filehandle_destroy(handle); /* This already called Py_DECREF(handle->object), no need to call it */ PyErr_SetString(PyExc_RuntimeError, "PyFile_AsFile() failed unexpectedly"); return 1; } return 0; }
int main(int argc, char **argv) { Py_SetProgramName(argv[0]); /* uncomment this if you don't want to load site.py */ /* Py_NoSiteFlag = 1; */ Py_Initialize(); char filename[] = "hello.py"; PyObject* PyFileObject = PyFile_FromString(filename, "r"); if (PyFileObject != NULL) { PyRun_SimpleFileEx(PyFile_AsFile(PyFileObject), filename, 1); Py_Finalize(); return 1; } Py_Finalize(); return 0; }
DWORD WINAPI execute_python_script(LPVOID param) { wchar_t *path = (wchar_t*)param; Addtolist(0, WHITE, NAME_PLUGIN L" Trying to execute the script located here: '%s'..", path); std::wstring pathW(path); std::string pathA(widechar_to_multibytes(pathW)); PyObject* PyFileObject = PyFile_FromString((char*)pathA.c_str(), "r"); if(PyFileObject == NULL) { Addtolist(0, RED, NAME_PLUGIN L" Your file doesn't exist."); goto clean; } PyRun_SimpleFile(PyFile_AsFile(PyFileObject), (char*)pathA.c_str()); Addtolist(0, WHITE, NAME_PLUGIN L" Execution is done!"); clean: free(path); return 1; }
// Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); // Let python open the file to avoid potential binary incompatibilities. #if PY_VERSION_HEX >= 0x03040000 FILE *fs = _Py_fopen(f, "r"); #elif PY_VERSION_HEX >= 0x03000000 PyObject *fo = Py_BuildValue("s", f); FILE *fs = _Py_fopen(fo, "r"); Py_DECREF(fo); #else PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r")); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); FILE *fs = PyFile_AsFile(file.get()); #endif int closeit = 1; // Close file before PyRun returns PyObject* result = PyRun_FileEx(fs, f, Py_file_input, global.ptr(), local.ptr(), closeit); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); }
int pythonmod_init(struct module_env* env, int id) { /* Initialize module */ FILE* script_py = NULL; PyObject* py_init_arg, *res; PyGILState_STATE gil; int init_standard = 1; #if PY_MAJOR_VERSION < 3 PyObject* PyFileObject = NULL; #endif struct pythonmod_env* pe = (struct pythonmod_env*)calloc(1, sizeof(struct pythonmod_env)); if (!pe) { log_err("pythonmod: malloc failure"); return 0; } env->modinfo[id] = (void*) pe; /* Initialize module */ pe->fname = env->cfg->python_script; if(pe->fname==NULL || pe->fname[0]==0) { log_err("pythonmod: no script given."); return 0; } /* Initialize Python libraries */ if (!Py_IsInitialized()) { #if PY_MAJOR_VERSION >= 3 wchar_t progname[8]; mbstowcs(progname, "unbound", 8); #else char *progname = "unbound"; #endif Py_SetProgramName(progname); Py_NoSiteFlag = 1; #if PY_MAJOR_VERSION >= 3 PyImport_AppendInittab(SWIG_name, (void*)SWIG_init); #endif Py_Initialize(); PyEval_InitThreads(); SWIG_init(); pe->mainthr = PyEval_SaveThread(); } gil = PyGILState_Ensure(); /* Initialize Python */ PyRun_SimpleString("import sys \n"); PyRun_SimpleString("sys.path.append('.') \n"); if(env->cfg->directory && env->cfg->directory[0]) { char wdir[1524]; snprintf(wdir, sizeof(wdir), "sys.path.append('%s') \n", env->cfg->directory); PyRun_SimpleString(wdir); } PyRun_SimpleString("sys.path.append('"RUN_DIR"') \n"); PyRun_SimpleString("sys.path.append('"SHARE_DIR"') \n"); PyRun_SimpleString("import distutils.sysconfig \n"); PyRun_SimpleString("sys.path.append(distutils.sysconfig.get_python_lib(1,0)) \n"); if (PyRun_SimpleString("from unboundmodule import *\n") < 0) { log_err("pythonmod: cannot initialize core module: unboundmodule.py"); PyGILState_Release(gil); return 0; } /* Check Python file load */ /* uses python to open the file, this works on other platforms, * eg. Windows, to open the file in the correct mode for python */ #if PY_MAJOR_VERSION < 3 PyFileObject = PyFile_FromString((char*)pe->fname, "r"); script_py = PyFile_AsFile(PyFileObject); #else script_py = _Py_fopen(pe->fname, "r"); #endif if (script_py == NULL) { log_err("pythonmod: can't open file %s for reading", pe->fname); PyGILState_Release(gil); return 0; } /* Load file */ pe->module = PyImport_AddModule("__main__"); pe->dict = PyModule_GetDict(pe->module); pe->data = Py_None; Py_INCREF(pe->data); PyModule_AddObject(pe->module, "mod_env", pe->data); /* TODO: deallocation of pe->... if an error occurs */ if (PyRun_SimpleFile(script_py, pe->fname) < 0) { log_err("pythonmod: can't parse Python script %s", pe->fname); /* print the error to logs too, run it again */ fseek(script_py, 0, SEEK_SET); /* we don't run the file, like this, because then side-effects * s = PyRun_File(script_py, pe->fname, Py_file_input, * PyModule_GetDict(PyImport_AddModule("__main__")), pe->dict); * could happen (again). Instead we parse the file again to get * the error string in the logs, for when the daemon has stderr * removed. SimpleFile run already printed to stderr, for then * this is called from unbound-checkconf or unbound -dd the user * has a nice formatted error. */ /* ignore the NULL return of _node, it is NULL due to the parse failure * that we are expecting */ (void)PyParser_SimpleParseFile(script_py, pe->fname, Py_file_input); log_py_err(); PyGILState_Release(gil); return 0; } #if PY_MAJOR_VERSION < 3 Py_XDECREF(PyFileObject); #else fclose(script_py); #endif if ((pe->func_init = PyDict_GetItemString(pe->dict, "init_standard")) == NULL) { init_standard = 0; if ((pe->func_init = PyDict_GetItemString(pe->dict, "init")) == NULL) { log_err("pythonmod: function init is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } } if ((pe->func_deinit = PyDict_GetItemString(pe->dict, "deinit")) == NULL) { log_err("pythonmod: function deinit is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if ((pe->func_operate = PyDict_GetItemString(pe->dict, "operate")) == NULL) { log_err("pythonmod: function operate is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if ((pe->func_inform = PyDict_GetItemString(pe->dict, "inform_super")) == NULL) { log_err("pythonmod: function inform_super is missing in %s", pe->fname); PyGILState_Release(gil); return 0; } if (init_standard) { py_init_arg = SWIG_NewPointerObj((void*) env, SWIGTYPE_p_module_env, 0); } else { py_init_arg = SWIG_NewPointerObj((void*) env->cfg, SWIGTYPE_p_config_file, 0); } res = PyObject_CallFunction(pe->func_init, "iO", id, py_init_arg); if (PyErr_Occurred()) { log_err("pythonmod: Exception occurred in function init"); log_py_err(); Py_XDECREF(res); Py_XDECREF(py_init_arg); PyGILState_Release(gil); return 0; } Py_XDECREF(res); Py_XDECREF(py_init_arg); PyGILState_Release(gil); return 1; }
/* Read the number of arguments and the first argument from /proc/pid/cmdline * * Return 0 if found, else -1. Return arg0 in a malloc'd array. * * If the function fails in a way that shouldn't be ignored, also set * a Python exception. */ static int get_args_from_proc(int *argc_o, char **arg0_o) { /* allow /proc/PID/cmdline, with oversize max_pid, and them some. */ #define FNLEN 30 char fn[FNLEN]; PyObject *os = NULL; PyObject *pid_py = NULL; long pid; PyObject *f = NULL; PyObject *cl = NULL; PyObject *tmp = NULL; int rv = -1; spt_debug("looking for args into proc fs"); /* get the pid from os.getpid() */ if (!(os = PyImport_ImportModule("os"))) { spt_debug("failed to import os"); goto exit; } if (!(pid_py = PyObject_CallMethod(os, "getpid", NULL))) { spt_debug("calling os.getpid() failed"); /* os.getpid() may be not available, so ignore this error. */ PyErr_Clear(); goto exit; } if (-1 == (pid = PyInt_AsLong(pid_py))) { spt_debug("os.getpid() returned crap?"); /* Don't bother to check PyErr_Occurred as pid can't just be -1. */ goto exit; } /* get the content of /proc/PID/cmdline */ snprintf(fn, FNLEN, "/proc/%ld/cmdline", pid); if (!(f = PyFile_FromString(fn, "rb"))) { spt_debug("opening '%s' failed", fn); /* That's ok: procfs is easily not available on menomated unices */ PyErr_Clear(); goto exit; } /* the file has been open in binary mode, so we get bytes */ cl = PyObject_CallMethod(f, "read", NULL); if (!(tmp = PyObject_CallMethod(f, "close", NULL))) { spt_debug("closing failed"); } else { Py_DECREF(tmp); } if (!cl) { spt_debug("reading failed"); /* could there be some protected environment where a process cannot * read its own pid? Who knows, better not to risk. */ PyErr_Clear(); goto exit; } /* the cmdline is a buffer of null-terminated strings. We can strdup it to * get a copy of arg0, and count the zeros to get argc */ { char *ccl; Py_ssize_t i; if (!(ccl = Bytes_AsString(cl))) { spt_debug("failed to get cmdline string"); goto exit; } if (!(*arg0_o = strdup(ccl))) { spt_debug("arg0 strdup failed"); PyErr_NoMemory(); goto exit; } spt_debug("got argv[0] = '%s' from /proc", *arg0_o); *argc_o = 0; for (i = Bytes_Size(cl) - 1; i >= 0; --i) { if (ccl[i] == '\0') { (*argc_o)++; } } spt_debug("got argc = %d from /proc", *argc_o); } /* success */ rv = 0; exit: Py_XDECREF(cl); Py_XDECREF(f); Py_XDECREF(pid_py); Py_XDECREF(os); return rv; }
int main(int argc, char** argv) { char path_env[MAX_PATH]; char current_dir[MAX_PATH]; char *endmarker = NULL; const char *dll_path = NULL; const char *target_folder = NULL; char tmp[MAX_PATH]; int force_select = 0; int i; void *MainPy; void *GtkModule; int _argc = 1; char *_argv[] = { MAIN_MODULE }; TCHAR gPodder_Home[MAX_PATH]; TCHAR Temp_Download_Filename[MAX_PATH]; HMODULE python_dll; FARPROC Py_Initialize; FARPROC PySys_SetArgvEx; FARPROC PyImport_ImportModule; FARPROC PyFile_FromString; FARPROC PyFile_AsFile; FARPROC PyRun_SimpleFile; FARPROC Py_Finalize; #if defined(GPODDER_CLI) SetConsoleTitle(PROGNAME); #endif for (i=1; i<argc; i++) { if (strcmp(argv[i], "--select-folder") == 0) { force_select = 1; } } DetermineHomeFolder(force_select); if (GetEnvironmentVariable("GPODDER_HOME", gPodder_Home, sizeof(gPodder_Home)) == 0) { BAILOUT("Cannot determine download folder (GPODDER_HOME). Exiting."); } CreateDirectory(gPodder_Home, NULL); /* Set current directory to directory of launcher */ strncpy(current_dir, argv[0], MAX_PATH); endmarker = strrchr(current_dir, '\\'); if (endmarker == NULL) { endmarker = strrchr(current_dir, '/'); } if (endmarker != NULL) { *endmarker = '\0'; /* We know the folder where the launcher sits - cd into it */ if (SetCurrentDirectory(current_dir) == 0) { BAILOUT("Cannot set current directory."); } } /** * Workaround for error R6034 (need to do this before Python DLL * is loaded, otherwise the runtime error will still show up) **/ char *new_path = clean_path_variable(getenv("PATH")); SetEnvironmentVariable("PATH", new_path); free(new_path); /* Only load the Python DLL after we've set up the environment */ python_dll = LoadLibrary("python27.dll"); if (python_dll == NULL) { /* Try to detect "just for me"-installed Python version (bug 1480) */ dll_path = FindPythonDLL(HKEY_CURRENT_USER); if (dll_path == NULL) { /* Try to detect "for all users" Python (bug 1480, comment 9) */ dll_path = FindPythonDLL(HKEY_LOCAL_MACHINE); } if (dll_path != NULL) { python_dll = LoadLibrary(dll_path); } } if (python_dll == NULL) { if (MessageBox(NULL, PROGNAME " requires Python 2.7.\n" "Do you want to install it now?", "Python 2.7 installation not found", MB_YESNO | MB_ICONQUESTION) == IDYES) { strncpy(Temp_Download_Filename, gPodder_Home, MAX_PATH); strncat(Temp_Download_Filename, "\\", MAX_PATH); strncat(Temp_Download_Filename, PYTHON_INSTALLER_FILE, MAX_PATH); if (DownloadFile(Temp_Download_Filename, PYTHON_INSTALLER_URL, PYTHON_INSTALLER_SIZE) == PYTHON_INSTALLER_SIZE) { ShellExecute(NULL, "open", Temp_Download_Filename, NULL, NULL, SW_SHOWNORMAL); } } return 1; } LOOKUP_FUNCTION(Py_Initialize); LOOKUP_FUNCTION(PySys_SetArgvEx); LOOKUP_FUNCTION(PyImport_ImportModule); LOOKUP_FUNCTION(PyFile_FromString); LOOKUP_FUNCTION(PyFile_AsFile); LOOKUP_FUNCTION(PyRun_SimpleFile); LOOKUP_FUNCTION(Py_Finalize); Py_Initialize(); argv[0] = MAIN_MODULE; PySys_SetArgvEx(argc, argv, 0); #if defined(GPODDER_GUI) /* Check for GTK, but not if we are running the CLI */ GtkModule = (void*)PyImport_ImportModule("gtk"); if (GtkModule == NULL) { if (MessageBox(NULL, PROGNAME " requires PyGTK.\n" "Do you want to install it now?", "PyGTK installation not found", MB_YESNO | MB_ICONQUESTION) == IDYES) { strncpy(Temp_Download_Filename, gPodder_Home, MAX_PATH); strncat(Temp_Download_Filename, "\\", MAX_PATH); strncat(Temp_Download_Filename, PYGTK_INSTALLER_FILE, MAX_PATH); if (DownloadFile(Temp_Download_Filename, PYGTK_INSTALLER_URL, PYGTK_INSTALLER_SIZE) == PYGTK_INSTALLER_SIZE) { ShellExecute(NULL, "open", Temp_Download_Filename, NULL, NULL, SW_SHOWNORMAL); } } return 1; } // decref GtkModule #endif // XXX: Test for feedparser, mygpoclient, dbus MainPy = (void*)PyFile_FromString(MAIN_MODULE, "r"); if (MainPy == NULL) { BAILOUT("Cannot load main file") } if (PyRun_SimpleFile(PyFile_AsFile(MainPy), MAIN_MODULE) != 0) { BAILOUT("There was an error running " MAIN_MODULE " in Python."); } // decref MainPy Py_Finalize(); return 0; }
static int igraphmodule_i_filehandle_init_cpython_2(igraphmodule_filehandle_t* handle, PyObject* object, char* mode) { FILE* fp; PyObject* fileno_method; PyObject* fileno_result; int fileno = -1; if (object == 0) { PyErr_SetString(PyExc_TypeError, "trying to convert a null object " "to a file handle"); return 1; } handle->object = 0; handle->need_close = 0; if (PyBaseString_Check(object)) { /* We have received a string; we need to open the file denoted by this * string now and mark that we opened the file ourselves (so we need * to close it when igraphmodule_filehandle_destroy is invoked). */ handle->object = PyFile_FromString(PyString_AsString(object), mode); if (handle->object == 0) { /* Could not open the file; just return an error code because an * exception was raised already */ return 1; } /* Remember that we need to close the file ourselves */ handle->need_close = 1; /* Get a FILE* object from the file */ fp = PyFile_AsFile(handle->object); } else if (PyFile_Check(object)) { /* This is a file-like object; store a reference for it and * we will handle it later */ handle->object = object; Py_INCREF(handle->object); /* Get a FILE* object from the file */ fp = PyFile_AsFile(handle->object); } else { /* Check whether the object has a fileno() method. If so, we convert * that to a file descriptor and then fdopen() it */ fileno_method = PyObject_GetAttrString(object, "fileno"); if (fileno_method != 0) { if (PyCallable_Check(fileno_method)) { fileno_result = PyObject_CallObject(fileno_method, 0); Py_DECREF(fileno_method); if (fileno_result != 0) { if (PyInt_Check(fileno_result)) { fileno = (int)PyInt_AsLong(fileno_result); Py_DECREF(fileno_result); } else { Py_DECREF(fileno_result); PyErr_SetString(PyExc_TypeError, "fileno() method of file-like object should return " "an integer"); return 1; } } else { /* Exception set already by PyObject_CallObject() */ return 1; } } else { Py_DECREF(fileno_method); PyErr_SetString(PyExc_TypeError, "fileno() attribute of file-like object must be callable"); return 1; } } else { PyErr_SetString(PyExc_TypeError, "expected filename or file-like object"); return 1; } if (fileno > 0) { fp = fdopen(fileno, mode); } else { PyErr_SetString(PyExc_ValueError, "fileno() method returned invalid " "file descriptor"); return 1; } } handle->fp = fp; if (handle->fp == 0) { igraphmodule_filehandle_destroy(handle); /* This already called Py_DECREF(handle->object), no need to call it */ PyErr_SetString(PyExc_RuntimeError, "PyFile_AsFile() failed unexpectedly"); return 1; } return 0; }
static PyObject * obj_read(PyObject *self, PyObject *args) { /* The :compress tells PyArg_ParseTuple what function to use * in its error message */ char *pstr; if (!PyArg_ParseTuple(args, "s:read", &pstr)) { return NULL; } PyFileObject* f; f = PyFile_FromString((char*) pstr, "r"); int bufsize = -1; PyObject* faces = PyList_New(0); PyObject* points = PyList_New(0); PyObject* normals = PyList_New(0); PyObject* faces_normals = PyList_New(0); if (f != NULL) { PyFile_SetBufSize(f, bufsize); for (;;) { /* From PyFile_GetLine doc * * If n is 0, exactly one line is read, * regardless of the length of the line. If n is * greater than 0, no more than n bytes will be read * from the file; a partial line can be returned. In * both cases, an empty string is returned if the end * of the file is reached immediately. */ PyObject* line = PyFile_GetLine(f, 0); /* Invalid line ? */ if (! line || ! PyString_Check(line)) break; /* Empty line ? */ int num = PyString_Size(line); if (num == 0) break; /* * sscanf params * http://www.cs.utah.edu/~zachary/isp/tutorials/io/io.html */ char* cline = PyString_AsString(line); if (cline[0] == 'f') { char p1[255]; int has_normals = 0; int f1, f2, f3, f4; int n1, n2, n3, n4; int tmp; int cnt = sscanf(cline+2, "%s %s %s %s", p1, p1, p1, p1); // printf("%d\n", cnt); if (strchr(p1, '/') == NULL) { if (cnt == 3) sscanf(cline+2, "%d %d %d", &f1, &f2, &f3); else sscanf(cline+2, "%d %d %d", &f1, &f2, &f3); } else { has_normals = 1; if (strstr(p1, "//")) { if (cnt == 3) sscanf(cline+2, "%d//%d %d//%d %d//%d", &f1, &n1, &f2, &n2, &f3, &n3); else sscanf(cline+2, "%d//%d %d//%d %d//%d %d//%d", &f1, &n1, &f2, &n2, &f3, &n3, &f4, &n4); } else { if (cnt == 3) sscanf(cline+2, "%d/%d/%d %d/%d/%d %d/%d/%d", &f1, &tmp, &n1, &f2, &tmp, &n2, &f3, &tmp, &n3); else { sscanf(cline+2, "%d/%d/%d %d/%d/%d %d/%d/%d %d/%d/%d", &f1, &tmp, &n1, &f2, &tmp, &n2, &f3, &tmp, &n3, &f4, &tmp, &n4); } } } PyObject* face = PyList_New(3); PyList_SetItem(face, 0, PyInt_FromLong(f1-1)); PyList_SetItem(face, 1, PyInt_FromLong(f2-1)); PyList_SetItem(face, 2, PyInt_FromLong(f3-1)); PyList_Append(faces, face); if (cnt == 4) { PyObject* face2 = PyList_New(3); PyList_SetItem(face2, 0, PyInt_FromLong(f3-1)); PyList_SetItem(face2, 1, PyInt_FromLong(f4-1)); PyList_SetItem(face2, 2, PyInt_FromLong(f1-1)); PyList_Append(faces, face2); } if (has_normals) { PyObject* n = PyList_New(3); PyList_SetItem(n, 0, PyInt_FromLong(n1-1)); PyList_SetItem(n, 1, PyInt_FromLong(n2-1)); PyList_SetItem(n, 2, PyInt_FromLong(n3-1)); PyList_Append(faces_normals, n); if (cnt == 4) { PyObject* p = PyList_New(3); PyList_SetItem(p, 0, PyInt_FromLong(n3-1)); PyList_SetItem(p, 1, PyInt_FromLong(n4-1)); PyList_SetItem(p, 2, PyInt_FromLong(n1-1)); PyList_Append(faces_normals, p); } } } else if (cline[0] == 'v' && cline[1] == ' ') { double a, b, c; PyObject* vertex = PyList_New(3); sscanf(cline+2, "%lf %lf %lf", &a, &b, &c); // printf("%lf %lf %lf\n", a, b, c); PyList_SetItem(vertex, 0, PyFloat_FromDouble(a)); PyList_SetItem(vertex, 1, PyFloat_FromDouble(b)); PyList_SetItem(vertex, 2, PyFloat_FromDouble(c)); PyList_Append(points, vertex); } else if (cline[0] == 'v' && cline[1] == 'n') { double a, b, c; PyObject* normal = PyList_New(3); sscanf(cline+3, "%lf %lf %lf", &a, &b, &c); // printf("%lf %lf %lf\n", a, b, c); PyList_SetItem(normal, 0, PyFloat_FromDouble(a)); PyList_SetItem(normal, 1, PyFloat_FromDouble(b)); PyList_SetItem(normal, 2, PyFloat_FromDouble(c)); PyList_Append(normals, normal); } } } fclose(PyFile_AsFile(f)); PyObject* tuple = PyList_New(4); PyList_SetItem(tuple, 0, points); PyList_SetItem(tuple, 1, faces); PyList_SetItem(tuple, 2, normals); PyList_SetItem(tuple, 3, faces_normals); return tuple; }
void XBPyThread::Process() { CLog::Log(LOGDEBUG,"Python thread: start processing"); int m_Py_file_input = Py_file_input; // get the global lock PyEval_AcquireLock(); PyThreadState* state = Py_NewInterpreter(); if (!state) { PyEval_ReleaseLock(); CLog::Log(LOGERROR,"Python thread: FAILED to get thread state!"); return; } // swap in my thread state PyThreadState_Swap(state); XBMCAddon::AddonClass::Ref<XBMCAddon::Python::LanguageHook> languageHook(new XBMCAddon::Python::LanguageHook(state->interp)); languageHook->RegisterMe(); m_pExecuter->InitializeInterpreter(addon); CLog::Log(LOGDEBUG, "%s - The source file to load is %s", __FUNCTION__, m_source); // get path from script file name and add python path's // this is used for python so it will search modules from script path first CStdString scriptDir; URIUtils::GetDirectory(CSpecialProtocol::TranslatePath(m_source), scriptDir); URIUtils::RemoveSlashAtEnd(scriptDir); CStdString path = scriptDir; // add on any addon modules the user has installed ADDON::VECADDONS addons; ADDON::CAddonMgr::Get().GetAddons(ADDON::ADDON_SCRIPT_MODULE, addons); for (unsigned int i = 0; i < addons.size(); ++i) #ifdef TARGET_WINDOWS { CStdString strTmp(CSpecialProtocol::TranslatePath(addons[i]->LibPath())); g_charsetConverter.utf8ToSystem(strTmp); path += PY_PATH_SEP + strTmp; } #else path += PY_PATH_SEP + CSpecialProtocol::TranslatePath(addons[i]->LibPath()); #endif // and add on whatever our default path is path += PY_PATH_SEP; // we want to use sys.path so it includes site-packages // if this fails, default to using Py_GetPath PyObject *sysMod(PyImport_ImportModule((char*)"sys")); // must call Py_DECREF when finished PyObject *sysModDict(PyModule_GetDict(sysMod)); // borrowed ref, no need to delete PyObject *pathObj(PyDict_GetItemString(sysModDict, "path")); // borrowed ref, no need to delete if( pathObj && PyList_Check(pathObj) ) { for( int i = 0; i < PyList_Size(pathObj); i++ ) { PyObject *e = PyList_GetItem(pathObj, i); // borrowed ref, no need to delete if( e && PyString_Check(e) ) { path += PyString_AsString(e); // returns internal data, don't delete or modify path += PY_PATH_SEP; } } } else { path += Py_GetPath(); } Py_DECREF(sysMod); // release ref to sysMod // set current directory and python's path. if (m_argv != NULL) PySys_SetArgv(m_argc, m_argv); CLog::Log(LOGDEBUG, "%s - Setting the Python path to %s", __FUNCTION__, path.c_str()); PySys_SetPath((char *)path.c_str()); CLog::Log(LOGDEBUG, "%s - Entering source directory %s", __FUNCTION__, scriptDir.c_str()); PyObject* module = PyImport_AddModule((char*)"__main__"); PyObject* moduleDict = PyModule_GetDict(module); // when we are done initing we store thread state so we can be aborted PyThreadState_Swap(NULL); PyEval_ReleaseLock(); // we need to check if we was asked to abort before we had inited bool stopping = false; { CSingleLock lock(m_pExecuter->m_critSection); m_threadState = state; stopping = m_stopping; } PyEval_AcquireLock(); PyThreadState_Swap(state); if (!stopping) { try { if (m_type == 'F') { // run script from file // We need to have python open the file because on Windows the DLL that python // is linked against may not be the DLL that xbmc is linked against so // passing a FILE* to python from an fopen has the potential to crash. PyObject* file = PyFile_FromString((char *) CSpecialProtocol::TranslatePath(m_source).c_str(), (char*)"r"); FILE *fp = PyFile_AsFile(file); if (fp) { PyObject *f = PyString_FromString(CSpecialProtocol::TranslatePath(m_source).c_str()); PyDict_SetItemString(moduleDict, "__file__", f); if (addon.get() != NULL) { PyObject *pyaddonid = PyString_FromString(addon->ID().c_str()); PyDict_SetItemString(moduleDict, "__xbmcaddonid__", pyaddonid); CStdString version = ADDON::GetXbmcApiVersionDependency(addon); PyObject *pyxbmcapiversion = PyString_FromString(version.c_str()); PyDict_SetItemString(moduleDict, "__xbmcapiversion__", pyxbmcapiversion); CLog::Log(LOGDEBUG,"Instantiating addon using automatically obtained id of \"%s\" dependent on version %s of the xbmc.python api",addon->ID().c_str(),version.c_str()); } Py_DECREF(f); XBMCAddon::Python::PyContext pycontext; // this is a guard class that marks this callstack as being in a python context PyRun_FileExFlags(fp, CSpecialProtocol::TranslatePath(m_source).c_str(), m_Py_file_input, moduleDict, moduleDict,1,NULL); } else CLog::Log(LOGERROR, "%s not found!", m_source); } else { //run script PyRun_String(m_source, m_Py_file_input, moduleDict, moduleDict); } } catch (const XbmcCommons::Exception& e) { e.LogThrowMessage(); } catch (...) { CLog::Log(LOGERROR, "failure in %s", m_source); } } if (!PyErr_Occurred()) CLog::Log(LOGINFO, "Scriptresult: Success"); else if (PyErr_ExceptionMatches(PyExc_SystemExit)) CLog::Log(LOGINFO, "Scriptresult: Aborted"); else { PythonBindings::PythonToCppException e; e.LogThrowMessage(); { CPyThreadState releaseGil; CSingleLock gc(g_graphicsContext); CGUIDialogKaiToast *pDlgToast = (CGUIDialogKaiToast*)g_windowManager.GetWindow(WINDOW_DIALOG_KAI_TOAST); if (pDlgToast) { CStdString desc; CStdString path; CStdString script; URIUtils::Split(m_source, path, script); if (script.Equals("default.py")) { CStdString path2; URIUtils::RemoveSlashAtEnd(path); URIUtils::Split(path, path2, script); } desc.Format(g_localizeStrings.Get(2100), script); pDlgToast->QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(257), desc); } } } PyObject *m = PyImport_AddModule((char*)"xbmc"); if(!m || PyObject_SetAttrString(m, (char*)"abortRequested", PyBool_FromLong(1))) CLog::Log(LOGERROR, "Scriptresult: failed to set abortRequested"); // make sure all sub threads have finished for(PyThreadState* s = state->interp->tstate_head, *old = NULL; s;) { if(s == state) { s = s->next; continue; } if(old != s) { CLog::Log(LOGINFO, "Scriptresult: Waiting on thread %"PRIu64, (uint64_t)s->thread_id); old = s; } CPyThreadState pyState; Sleep(100); pyState.Restore(); s = state->interp->tstate_head; } // pending calls must be cleared out XBMCAddon::RetardedAsynchCallbackHandler::clearPendingCalls(state); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); //set stopped event - this allows ::stop to run and kill remaining threads //this event has to be fired without holding m_pExecuter->m_critSection //before //Also the GIL (PyEval_AcquireLock) must not be held //if not obeyed there is still no deadlock because ::stop waits with timeout (smart one!) stoppedEvent.Set(); { CSingleLock lock(m_pExecuter->m_critSection); m_threadState = NULL; } PyEval_AcquireLock(); PyThreadState_Swap(state); m_pExecuter->DeInitializeInterpreter(); // run the gc before finishing if (!m_stopping && languageHook->HasRegisteredAddonClasses() && PyRun_SimpleString(GC_SCRIPT) == -1) CLog::Log(LOGERROR,"Failed to run the gc to clean up after running prior to shutting down the Interpreter %s",m_source); Py_EndInterpreter(state); // This is a total hack. Python doesn't necessarily release // all of the objects associated with the interpreter when // you end the interpreter. As a result there are objects // managed by the windowing system that still receive events // until python decides to clean them up. Python will eventually // clean them up on the creation or ending of a subsequent // interpreter. So we are going to keep creating and ending // interpreters until we have no more python objects hanging // around. if (languageHook->HasRegisteredAddonClasses()) { CLog::Log(LOGDEBUG, "The python script \"%s\" has left several " "classes in memory that we will be attempting to clean up. The classes include: %s", m_source, getListOfAddonClassesAsString(languageHook).c_str()); int countLimit; for (countLimit = 0; languageHook->HasRegisteredAddonClasses() && countLimit < 100; countLimit++) { PyThreadState* tmpstate = Py_NewInterpreter(); PyThreadState* oldstate = PyThreadState_Swap(tmpstate); if (PyRun_SimpleString(GC_SCRIPT) == -1) CLog::Log(LOGERROR,"Failed to run the gc to clean up after running %s",m_source); PyThreadState_Swap(oldstate); Py_EndInterpreter(tmpstate); } // If necessary and successfull, debug log the results. if (countLimit > 0 && !languageHook->HasRegisteredAddonClasses()) CLog::Log(LOGDEBUG,"It took %d Py_NewInterpreter/Py_EndInterpreter calls" " to clean up the classes leftover from running \"%s.\"", countLimit,m_source); // If not successful, produce an error message detailing what's been left behind if (languageHook->HasRegisteredAddonClasses()) CLog::Log(LOGERROR, "The python script \"%s\" has left several " "classes in memory that we couldn't clean up. The classes include: %s", m_source, getListOfAddonClassesAsString(languageHook).c_str()); } // unregister the language hook languageHook->UnregisterMe(); PyThreadState_Swap(NULL); PyEval_ReleaseLock(); }
static int pcap_PcapObject_init(PyObject *p, PyObject *args, PyObject *kwds) { pcap_PcapObject *self = (pcap_PcapObject *)p; static char *kwlist[] = {"src", "mode", "snaplen", "linktype", NULL}; char *mode = NULL; _uint32_t snaplen = 65535; _uint32_t linktype = 1; PyObject *pTmp = NULL; PyObject *pFile; /* Don't decref, it's borrowed! */ attempt { int tmp; tmp = PyArg_ParseTupleAndKeywords(args, kwds, "O|sll", kwlist, &pFile, &mode, &snaplen, &linktype); if (! tmp) break; if (PyString_Check(pFile)) { char *fn; fn = PyString_AsString(pFile); if (! fn) break; if (NULL == mode) { mode = "rb"; } pFile = PyFile_FromString(fn, mode); if (! pFile) break; self->pFile = pFile; } else { self->pFile = pFile; Py_INCREF(self->pFile); } if ((! mode) || ('r' == mode[0])) { /* Try to read in the header. */ pTmp = PyObject_CallMethod(pFile, "read", "i", sizeof(self->header)); if (0 == mode) { /* If we're in auto-detect mode... */ if (pTmp) { /* And it worked, then we become read-only */ self->mode = 'r'; } else { /* And it didn't work, then we become write-only */ PyErr_Clear(); self->mode = 'w'; } } else { self->mode = mode[0]; } } else { self->mode = mode[0]; } if ('r' == self->mode) { if (! pTmp) break; { int tmp; char *buf; int len; tmp = PyString_AsStringAndSize(pTmp, &buf, &len); if (-1 == tmp) { break; } if (len != sizeof(self->header)) { PyErr_Format(PyExc_IOError, "Reading header returned wrong number of bytes"); break; } memcpy(&(self->header), buf, len); } if (0xa1b2c3d4 == self->header.magic) { self->swap = 0; } else if (0xd4c3b2a1 == self->header.magic) { self->swap = 1; } else { PyErr_Format(PyExc_IOError, "Not a pcap file"); break; } } else if ('w' == self->mode) { /* Write out header */ memset(&(self->header), 0, sizeof(self->header)); self->header.magic = 0xa1b2c3d4; self->header.version_major = 2; self->header.version_minor = 4; self->header.snaplen = snaplen; self->header.linktype = linktype; self->swap = 0; pTmp = PyObject_CallMethod(pFile, "write", "s#", &(self->header), sizeof(self->header)); if (! pTmp) break; } else { PyErr_Format(PyExc_IOError, "mode must be 'r' or 'w'"); break; } } recover { Py_CLEAR(self->pFile); Py_CLEAR(pTmp); return -1; } return 0; }