PyFrameObject * PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals, PyObject *locals) { PyFrameObject *back = tstate->frame; PyFrameObject *f; PyObject *builtins; Py_ssize_t i; #ifdef Py_DEBUG if (code == NULL || globals == NULL || !PyDict_Check(globals) || (locals != NULL && !PyMapping_Check(locals))) { PyErr_BadInternalCall(); return NULL; } #endif if (back == NULL || back->f_globals != globals) { builtins = _PyDict_GetItemId(globals, &PyId___builtins__); if (builtins) { if (PyModule_Check(builtins)) { builtins = PyModule_GetDict(builtins); assert(builtins != NULL); } } if (builtins == NULL) { /* No builtins! Make up a minimal one Give them 'None', at least. */ builtins = PyDict_New(); if (builtins == NULL || PyDict_SetItemString( builtins, "None", Py_None) < 0) return NULL; } else Py_INCREF(builtins); } else { /* If we share the globals, we share the builtins. Save a lookup and a call. */ builtins = back->f_builtins; assert(builtins != NULL); Py_INCREF(builtins); } if (code->co_zombieframe != NULL) { f = code->co_zombieframe; code->co_zombieframe = NULL; _Py_NewReference((PyObject *)f); assert(f->f_code == code); } else { Py_ssize_t extras, ncells, nfrees; ncells = PyTuple_GET_SIZE(code->co_cellvars); nfrees = PyTuple_GET_SIZE(code->co_freevars); extras = code->co_stacksize + code->co_nlocals + ncells + nfrees; if (free_list == NULL) { f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type, extras); if (f == NULL) { Py_DECREF(builtins); return NULL; } } else { assert(numfree > 0); --numfree; f = free_list; free_list = free_list->f_back; if (Py_SIZE(f) < extras) { PyFrameObject *new_f = PyObject_GC_Resize(PyFrameObject, f, extras); if (new_f == NULL) { PyObject_GC_Del(f); Py_DECREF(builtins); return NULL; } f = new_f; } _Py_NewReference((PyObject *)f); } f->f_code = code; extras = code->co_nlocals + ncells + nfrees; f->f_valuestack = f->f_localsplus + extras; for (i=0; i<extras; i++) f->f_localsplus[i] = NULL; f->f_locals = NULL; f->f_trace = NULL; f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL; } f->f_stacktop = f->f_valuestack; f->f_builtins = builtins; Py_XINCREF(back); f->f_back = back; Py_INCREF(code); Py_INCREF(globals); f->f_globals = globals; /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */ if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) == (CO_NEWLOCALS | CO_OPTIMIZED)) ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */ else if (code->co_flags & CO_NEWLOCALS) { locals = PyDict_New(); if (locals == NULL) { Py_DECREF(f); return NULL; } f->f_locals = locals; } else { if (locals == NULL) locals = globals; Py_INCREF(locals); f->f_locals = locals; } f->f_tstate = tstate; f->f_lasti = -1; f->f_lineno = code->co_firstlineno; f->f_iblock = 0; f->f_executing = 0; f->f_gen = NULL; _PyObject_GC_TRACK(f); return f; }
static void fixup_ulcase(void) { PyObject *mods, *strop, *string, *ulo; unsigned char ul[256]; int n, c; /* find the string and strop modules */ mods = PyImport_GetModuleDict(); if (!mods) return; string = PyDict_GetItemString(mods, "string"); if (string) string = PyModule_GetDict(string); strop=PyDict_GetItemString(mods, "strop"); if (strop) strop = PyModule_GetDict(strop); if (!string && !strop) return; /* create uppercase map string */ n = 0; for (c = 0; c < 256; c++) { if (isupper(c)) ul[n++] = c; } ulo = PyString_FromStringAndSize((const char *)ul, n); if (!ulo) return; if (string) PyDict_SetItemString(string, "uppercase", ulo); if (strop) PyDict_SetItemString(strop, "uppercase", ulo); Py_DECREF(ulo); /* create lowercase string */ n = 0; for (c = 0; c < 256; c++) { if (islower(c)) ul[n++] = c; } ulo = PyString_FromStringAndSize((const char *)ul, n); if (!ulo) return; if (string) PyDict_SetItemString(string, "lowercase", ulo); if (strop) PyDict_SetItemString(strop, "lowercase", ulo); Py_DECREF(ulo); /* create letters string */ n = 0; for (c = 0; c < 256; c++) { if (isalpha(c)) ul[n++] = c; } ulo = PyString_FromStringAndSize((const char *)ul, n); if (!ulo) return; if (string) PyDict_SetItemString(string, "letters", ulo); Py_DECREF(ulo); }
void ChPythonEngine::ImportSolidWorksSystem(const char* solidworks_py_file, ChSystem& msystem) throw(ChException) { std::ostringstream sstream; //sstream << "from " << std::string(solidworks_py_file) << " import exported_items\n"; sstream << "import builtins \n"; sstream << "import imp \n"; sstream << "import os \n"; sstream << "mdirname, mmodulename= os.path.split('" << std::string(solidworks_py_file) << "') \n"; sstream << "builtins.exported_system_relpath = mdirname + '/' \n"; sstream << "fp, pathname, description = imp.find_module(mmodulename,[builtins.exported_system_relpath]) \n"; sstream << "try: \n"; sstream << " imported_mod = imp.load_module('imported_mod', fp, pathname, description) \n"; sstream << "finally: \n"; sstream << " if fp: \n"; sstream << " fp.close() \n"; sstream << "exported_items = imported_mod.exported_items \n"; this->Run(sstream.str().c_str()); PyObject * module = PyImport_AddModule("__main__"); // borrowed reference if (!module) throw ChException("ERROR. No Python __main__ module?"); PyObject * dictionary = PyModule_GetDict(module); // borrowed reference if (!dictionary) throw ChException("ERROR. No Python dictionary?"); PyObject * result = PyDict_GetItemString(dictionary, "exported_items"); // borrowed reference if (!result) throw ChException("ERROR. Missing Python object 'exported_items' in SolidWorks file"); if (PyList_Check(result)) { int nitems = PyList_Size(result); //GetLog() << "N.of list items: " << nitems << "\n"; for (int i = 0; i< nitems; i++) { PyObject* mobj = PyList_GetItem(result,i); if (mobj) { // GetLog() << " Python type: " << mobj->ob_type->tp_name << "\n"; SwigPyObject * mswigobj = SWIG_Python_GetSwigThis(mobj); if (mswigobj) { void* objptr = mswigobj->ptr; ChSharedPtr<ChPhysicsItem>* pt_to_shp = (ChSharedPtr<ChPhysicsItem>*)objptr; /// Add the ChPhysicsItem to the ChSystem msystem.Add( (*pt_to_shp) ); } else { throw ChException("ERROR. Only shared pointers to ChPhysicsItem subclasses can be inside exported_items."); } } } msystem.Setup(); msystem.Update(); } else { throw ChException("ERROR. exported_items python object is not a list."); } }
PyMODINIT_FUNC initzbar (void) { /* initialize types */ zbarEnumItem_Type.tp_base = &PyInt_Type; zbarException_Type.tp_base = (PyTypeObject*)PyExc_Exception; if(PyType_Ready(&zbarException_Type) < 0 || PyType_Ready(&zbarEnumItem_Type) < 0 || PyType_Ready(&zbarEnum_Type) < 0 || PyType_Ready(&zbarImage_Type) < 0 || PyType_Ready(&zbarSymbol_Type) < 0 || PyType_Ready(&zbarSymbolSet_Type) < 0 || PyType_Ready(&zbarSymbolIter_Type) < 0 || PyType_Ready(&zbarProcessor_Type) < 0 || PyType_Ready(&zbarImageScanner_Type) < 0 || PyType_Ready(&zbarDecoder_Type) < 0 || PyType_Ready(&zbarScanner_Type) < 0) return; /* initialize constant containers */ config_enum = zbarEnum_New(); modifier_enum = zbarEnum_New(); symbol_enum = PyDict_New(); orient_enum = zbarEnum_New(); if(!config_enum || !modifier_enum || !symbol_enum || !orient_enum) return; zbar_exc[0] = (PyObject*)&zbarException_Type; zbar_exc[ZBAR_ERR_NOMEM] = NULL; zbar_error_t ei; for(ei = ZBAR_ERR_INTERNAL; ei < ZBAR_ERR_NUM; ei++) { zbar_exc[ei] = PyErr_NewException(exc_names[ei], zbar_exc[0], NULL); if(!zbar_exc[ei]) return; } /* internally created/read-only type overrides */ zbarEnum_Type.tp_new = NULL; zbarEnum_Type.tp_setattr = NULL; zbarEnum_Type.tp_setattro = NULL; /* initialize module */ PyObject *mod = Py_InitModule("zbar", zbar_functions); if(!mod) return; /* add types to module */ PyModule_AddObject(mod, "EnumItem", (PyObject*)&zbarEnumItem_Type); PyModule_AddObject(mod, "Image", (PyObject*)&zbarImage_Type); PyModule_AddObject(mod, "Config", (PyObject*)config_enum); PyModule_AddObject(mod, "Modifier", (PyObject*)modifier_enum); PyModule_AddObject(mod, "Orient", (PyObject*)orient_enum); PyModule_AddObject(mod, "Symbol", (PyObject*)&zbarSymbol_Type); PyModule_AddObject(mod, "SymbolSet", (PyObject*)&zbarSymbolSet_Type); PyModule_AddObject(mod, "SymbolIter", (PyObject*)&zbarSymbolIter_Type); PyModule_AddObject(mod, "Processor", (PyObject*)&zbarProcessor_Type); PyModule_AddObject(mod, "ImageScanner", (PyObject*)&zbarImageScanner_Type); PyModule_AddObject(mod, "Decoder", (PyObject*)&zbarDecoder_Type); PyModule_AddObject(mod, "Scanner", (PyObject*)&zbarScanner_Type); for(ei = 0; ei < ZBAR_ERR_NUM; ei++) if(zbar_exc[ei]) PyModule_AddObject(mod, exc_names[ei] + 5, zbar_exc[ei]); /* add constants */ PyObject *dict = PyModule_GetDict(mod); color_enum[ZBAR_SPACE] = zbarEnumItem_New(dict, NULL, ZBAR_SPACE, "SPACE"); color_enum[ZBAR_BAR] = zbarEnumItem_New(dict, NULL, ZBAR_BAR, "BAR"); const enumdef *item; for(item = config_defs; item->strval; item++) zbarEnum_Add(config_enum, item->intval, item->strval); for(item = modifier_defs; item->strval; item++) zbarEnum_Add(modifier_enum, item->intval, item->strval); for(item = orient_defs; item->strval; item++) zbarEnum_Add(orient_enum, item->intval, item->strval); PyObject *tp_dict = zbarSymbol_Type.tp_dict; for(item = symbol_defs; item->strval; item++) zbarEnumItem_New(tp_dict, symbol_enum, item->intval, item->strval); symbol_NONE = zbarSymbol_LookupEnum(ZBAR_NONE); }
static int Python3_Init(void) { if (!py3initialised) { #ifdef DYNAMIC_PYTHON3 if (!python3_enabled(TRUE)) { EMSG(_("E263: Sorry, this command is disabled, the Python library could not be loaded.")); goto fail; } #endif init_structs(); #ifdef PYTHON3_HOME Py_SetPythonHome(PYTHON3_HOME); #endif PyImport_AppendInittab("vim", Py3Init_vim); #if !defined(MACOS) || defined(MACOS_X_UNIX) Py_Initialize(); #else PyMac_Initialize(); #endif /* Initialise threads, and below save the state using * PyEval_SaveThread. Without the call to PyEval_SaveThread, thread * specific state (such as the system trace hook), will be lost * between invocations of Python code. */ PyEval_InitThreads(); #ifdef DYNAMIC_PYTHON3 get_py3_exceptions(); #endif if (PythonIO_Init_io()) goto fail; globals = PyModule_GetDict(PyImport_AddModule("__main__")); /* Remove the element from sys.path that was added because of our * argv[0] value in Py3Init_vim(). Previously we used an empty * string, but depending on the OS we then get an empty entry or * the current directory in sys.path. * Only after vim has been imported, the element does exist in * sys.path. */ PyRun_SimpleString("import vim; import sys; sys.path = list(filter(lambda x: not x.endswith('must>not&exist'), sys.path))"); /* lock is created and acquired in PyEval_InitThreads() and thread * state is created in Py_Initialize() * there _PyGILState_NoteThreadState() also sets gilcounter to 1 * (python must have threads enabled!) * so the following does both: unlock GIL and save thread state in TLS * without deleting thread state */ PyEval_SaveThread(); py3initialised = 1; } return 0; fail: /* We call PythonIO_Flush() here to print any Python errors. * This is OK, as it is possible to call this function even * if PythonIO_Init_io() has not completed successfully (it will * not do anything in this case). */ PythonIO_Flush(); return -1; }
void _Py_InitializeEx_Private(int install_sigs, int install_importlib) { PyInterpreterState *interp; PyThreadState *tstate; PyObject *bimod, *sysmod, *pstderr; char *p; extern void _Py_ReadyTypes(void); if (initialized) return; initialized = 1; _Py_Finalizing = NULL; #if defined(HAVE_LANGINFO_H) && defined(HAVE_SETLOCALE) /* Set up the LC_CTYPE locale, so we can obtain the locale's charset without having to switch locales. */ setlocale(LC_CTYPE, ""); #endif if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0') Py_DebugFlag = add_flag(Py_DebugFlag, p); if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0') Py_VerboseFlag = add_flag(Py_VerboseFlag, p); if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0') Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p); if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0') Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p); /* The variable is only tested for existence here; _PyRandom_Init will check its value further. */ if ((p = Py_GETENV("PYTHONHASHSEED")) && *p != '\0') Py_HashRandomizationFlag = add_flag(Py_HashRandomizationFlag, p); _PyRandom_Init(); interp = PyInterpreterState_New(); if (interp == NULL) Py_FatalError("Py_Initialize: can't make first interpreter"); tstate = PyThreadState_New(interp); if (tstate == NULL) Py_FatalError("Py_Initialize: can't make first thread"); (void) PyThreadState_Swap(tstate); #ifdef WITH_THREAD /* We can't call _PyEval_FiniThreads() in Py_FinalizeEx because destroying the GIL might fail when it is being referenced from another running thread (see issue #9901). Instead we destroy the previously created GIL here, which ensures that we can call Py_Initialize / Py_FinalizeEx multiple times. */ _PyEval_FiniThreads(); /* Auto-thread-state API */ _PyGILState_Init(interp, tstate); #endif /* WITH_THREAD */ _Py_ReadyTypes(); if (!_PyFrame_Init()) Py_FatalError("Py_Initialize: can't init frames"); if (!_PyLong_Init()) Py_FatalError("Py_Initialize: can't init longs"); if (!PyByteArray_Init()) Py_FatalError("Py_Initialize: can't init bytearray"); if (!_PyFloat_Init()) Py_FatalError("Py_Initialize: can't init float"); interp->modules = PyDict_New(); if (interp->modules == NULL) Py_FatalError("Py_Initialize: can't make modules dictionary"); /* Init Unicode implementation; relies on the codec registry */ if (_PyUnicode_Init() < 0) Py_FatalError("Py_Initialize: can't initialize unicode"); if (_PyStructSequence_Init() < 0) Py_FatalError("Py_Initialize: can't initialize structseq"); bimod = _PyBuiltin_Init(); if (bimod == NULL) Py_FatalError("Py_Initialize: can't initialize builtins modules"); _PyImport_FixupBuiltin(bimod, "builtins"); interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) Py_FatalError("Py_Initialize: can't initialize builtins dict"); Py_INCREF(interp->builtins); /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PySys_Init(); if (sysmod == NULL) Py_FatalError("Py_Initialize: can't initialize sys"); interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) Py_FatalError("Py_Initialize: can't initialize sys dict"); Py_INCREF(interp->sysdict); _PyImport_FixupBuiltin(sysmod, "sys"); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImport_Init(); _PyImportHooks_Init(); /* Initialize _warnings. */ _PyWarnings_Init(); if (!install_importlib) return; if (_PyTime_Init() < 0) Py_FatalError("Py_Initialize: can't initialize time"); import_init(interp, sysmod); /* initialize the faulthandler module */ if (_PyFaulthandler_Init()) Py_FatalError("Py_Initialize: can't initialize faulthandler"); if (initfsencoding(interp) < 0) Py_FatalError("Py_Initialize: unable to load the file system codec"); if (install_sigs) initsigs(); /* Signal handling stuff, including initintr() */ if (_PyTraceMalloc_Init() < 0) Py_FatalError("Py_Initialize: can't initialize tracemalloc"); initmain(interp); /* Module __main__ */ if (initstdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); /* Initialize warnings. */ if (PySys_HasWarnOptions()) { PyObject *warnings_module = PyImport_ImportModule("warnings"); if (warnings_module == NULL) { fprintf(stderr, "'import warnings' failed; traceback:\n"); PyErr_Print(); } Py_XDECREF(warnings_module); } if (!Py_NoSiteFlag) initsite(); /* Module site */ }
PyMODINIT_FUNC initumath(void) #endif { PyObject *m, *d, *s, *s2, *c_api; int UFUNC_FLOATING_POINT_SUPPORT = 1; #ifdef NO_UFUNC_FLOATING_POINT_SUPPORT UFUNC_FLOATING_POINT_SUPPORT = 0; #endif /* Create the module and add the functions */ #if defined(NPY_PY3K) m = PyModule_Create(&moduledef); #else m = Py_InitModule("umath", methods); #endif if (!m) { return RETVAL; } /* Import the array */ if (_import_array() < 0) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "umath failed: Could not import array core."); } return RETVAL; } /* Initialize the types */ if (PyType_Ready(&PyUFunc_Type) < 0) return RETVAL; /* Add some symbolic constants to the module */ d = PyModule_GetDict(m); c_api = NpyCapsule_FromVoidPtr((void *)PyUFunc_API, NULL); if (PyErr_Occurred()) { goto err; } PyDict_SetItemString(d, "_UFUNC_API", c_api); Py_DECREF(c_api); if (PyErr_Occurred()) { goto err; } s = PyString_FromString("0.4.0"); PyDict_SetItemString(d, "__version__", s); Py_DECREF(s); /* Load the ufunc operators into the array module's namespace */ InitOperators(d); PyDict_SetItemString(d, "pi", s = PyFloat_FromDouble(NPY_PI)); Py_DECREF(s); PyDict_SetItemString(d, "e", s = PyFloat_FromDouble(NPY_E)); Py_DECREF(s); PyDict_SetItemString(d, "euler_gamma", s = PyFloat_FromDouble(NPY_EULER)); Py_DECREF(s); #define ADDCONST(str) PyModule_AddIntConstant(m, #str, UFUNC_##str) #define ADDSCONST(str) PyModule_AddStringConstant(m, "UFUNC_" #str, UFUNC_##str) ADDCONST(ERR_IGNORE); ADDCONST(ERR_WARN); ADDCONST(ERR_CALL); ADDCONST(ERR_RAISE); ADDCONST(ERR_PRINT); ADDCONST(ERR_LOG); ADDCONST(ERR_DEFAULT); ADDCONST(SHIFT_DIVIDEBYZERO); ADDCONST(SHIFT_OVERFLOW); ADDCONST(SHIFT_UNDERFLOW); ADDCONST(SHIFT_INVALID); ADDCONST(FPE_DIVIDEBYZERO); ADDCONST(FPE_OVERFLOW); ADDCONST(FPE_UNDERFLOW); ADDCONST(FPE_INVALID); ADDCONST(FLOATING_POINT_SUPPORT); ADDSCONST(PYVALS_NAME); #undef ADDCONST #undef ADDSCONST PyModule_AddIntConstant(m, "UFUNC_BUFSIZE_DEFAULT", (long)NPY_BUFSIZE); PyModule_AddObject(m, "PINF", PyFloat_FromDouble(NPY_INFINITY)); PyModule_AddObject(m, "NINF", PyFloat_FromDouble(-NPY_INFINITY)); PyModule_AddObject(m, "PZERO", PyFloat_FromDouble(NPY_PZERO)); PyModule_AddObject(m, "NZERO", PyFloat_FromDouble(NPY_NZERO)); PyModule_AddObject(m, "NAN", PyFloat_FromDouble(NPY_NAN)); #if defined(NPY_PY3K) s = PyDict_GetItemString(d, "true_divide"); PyDict_SetItemString(d, "divide", s); #endif s = PyDict_GetItemString(d, "conjugate"); s2 = PyDict_GetItemString(d, "remainder"); /* Setup the array object's numerical structures with appropriate ufuncs in d*/ PyArray_SetNumericOps(d); PyDict_SetItemString(d, "conj", s); PyDict_SetItemString(d, "mod", s2); initscalarmath(m); if (!intern_strings()) { goto err; } return RETVAL; err: /* Check for errors */ if (!PyErr_Occurred()) { PyErr_SetString(PyExc_RuntimeError, "cannot load umath module."); } return RETVAL; }
PyMODINIT_FUNC PyInit_soy_widgets(void) { PyObject *module, *dict; ///////////////////////////////////////////////////////////////////////// // Initialize all types prior to module creation // // int PyType_Ready(PyTypeObject*) // Finalize a type object. This should be called on all type objects to // finish their initialization. This function is responsible for adding // inherited slots from a type's base class. // Return 0 on success, or return -1 and sets an exception on error. // init Widget type PYSOY_TYPEINIT(widgets, Widget); // init Canvas type PYSOY_TYPEINIT(widgets, Canvas); // init Container type PYSOY_TYPEINIT(widgets, Container); // init HBox type PYSOY_TYPEINIT(widgets, HBox); // init HBox type PYSOY_TYPEINIT(widgets, VBox); // init Projector type PYSOY_TYPEINIT(widgets, Projector); // init Window type PYSOY_TYPEINIT(widgets, Window); // additional types above this line in alphabetical order ///////////////////////////////////////////////////////////////////////// module = PyModule_Create(&module_def); dict = PyModule_GetDict(module); // add additional pydoc strings PyModule_AddStringConstant(module, "__credits__", PYSOY_CREDITS); PyModule_AddStringConstant(module, "__version__", SOY_VERSION); ///////////////////////////////////////////////////////////////////////// // add each type to the module object // add Widget type PYSOY_TYPEADD_G(widgets, widget, Widget); // add Canvas type PYSOY_TYPEADD_G(widgets, canvas, Canvas); // add Container type PYSOY_TYPEADD_G(widgets, container, Container); // add HBox type PYSOY_TYPEADD_G(widgets, hbox, HBox); // add VBox type PYSOY_TYPEADD_G(widgets, vbox, VBox); // add Projector type PYSOY_TYPEADD_G(widgets, projector, Projector); // add Window type PYSOY_TYPEADD_G(widgets, window, Window); // additional types above this line in alphabetical order ///////////////////////////////////////////////////////////////////////// if (PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "PySoy_widgets: init failed"); return NULL; } else return module; }
/*-------------------------------------------------------------------------------*/ struct rest_response * start_intercloudGW( struct occi_category * optr, struct rest_client * cptr, struct rest_request * rptr, struct rest_response * aptr, void * vptr ) { struct intercloudGW * pptr; char sendstr[1024]=" "; char strtmp[1024]=" "; int status; char message[1024]; char srcdir[1024]; char * response = NULL; char * token; FILE * exp_file; listcc restResponse; PyObject *pName=NULL, *pModule=NULL, *pDict=NULL, *pFunc=NULL,*result=NULL; PyThreadState* pythr=NULL; if (!( pptr = vptr )) return( rest_html_response( aptr, 404, "Invalid Action" ) ); else{ if(!(pptr->name))strcpy(sendstr," "); else if(pptr->name[0]=='\0') strcpy(sendstr," "); else strcpy(sendstr,pptr->name); if(!(pptr->node)){ strcpy(strtmp," "); strConcat(sendstr,strtmp,','); } else if(pptr->node[0]=='\0'){ strcpy(strtmp," "); strConcat(sendstr,strtmp,','); } else strConcat(sendstr,pptr->node,','); if(!(pptr->account)){ strcpy(strtmp," "); strConcat(sendstr,strtmp,','); } else if(pptr->account[0]=='\0'){ strcpy(strtmp," "); strConcat(sendstr,strtmp,','); } else strConcat(sendstr,pptr->account,','); if(!(pptr->price)){ strcpy(strtmp," "); strConcat(sendstr,strtmp,','); } else if(pptr->price[0]=='\0'){ strcpy(strtmp," "); strConcat(sendstr,strtmp,','); } else strConcat(sendstr,pptr->price,','); if(!(pptr->state)){ strcpy(strtmp," "); strConcat(sendstr,strtmp,','); } else if(pptr->state[0]=='\0'){ strcpy(strtmp," "); strConcat(sendstr,strtmp,','); } else strConcat(sendstr,pptr->state,','); // python interface sprintf(srcdir,"%s/pyaccords/pysrc",PYPATH); pythr = Py_NewInterpreter(); python_path(srcdir); pName = PyString_FromString("intercloudGWAct"); if(pName == NULL) printf("erro: in intercloudGWAct no such file name\n"); else pModule = PyImport_Import(pName); if(pModule == NULL) printf("error: failed to load intercloudGWAct module\n"); else pDict = PyModule_GetDict(pModule); if(pDict == NULL) printf("error: failed to load dict name in intercloudGW module\n"); else pFunc = PyDict_GetItemString(pDict,"start"); if(pFunc == NULL) printf("error: failed to load start function in intercloudGW module\n"); else result=PyObject_CallFunction(pFunc,"s",sendstr); if(result) response=allocate_string(PyString_AsString( result )); Py_DECREF(pModule); Py_DECREF(pName); Py_EndInterpreter(pythr); resetListe(&restResponse); token= strtok(response,","); for(; token != NULL ;) { addBacke(&restResponse,token); token=strtok(NULL, ","); } elemm *pelem = restResponse.first; if(pelem){ status = atoi(pelem->value); pelem = pelem->next; } if(pelem){ strcpy(message, pelem->value); pelem = pelem->next; } return( rest_html_response( aptr, status, message ) ); } }
static void * download_thread(void *p_tasks) { if (p_tasks == NULL) { return NULL; } pydownload_tasks_t *thread_tasks = (pydownload_tasks_t *)p_tasks; // initial the py environment PyObject *pName, *pModule, *pDict, *pFunc_download; int tsize = thread_tasks->task_buffer.size(); int Py_Init_OK; try { Py_Initialize(); Py_Init_OK = Py_IsInitialized(); if (!Py_Init_OK) { throw std::runtime_error("Py environment initial error"); } PyRun_SimpleString(PY_IMPORT_SYS_MODULE_CMD); PyRun_SimpleString(PY_APD_DOWNLOAD_PATH_CMD); // append the py file path pName = PyString_FromString(PY_DOWNLOAD_MODULE_NAME); // convert to module name object pModule = PyImport_Import(pName); if (pModule == NULL) { throw std::runtime_error("Py import module failed"); } pDict = PyModule_GetDict(pModule); if (pDict == NULL) { throw std::runtime_error("Py module get dict failed"); } pFunc_download = PyDict_GetItemString(pDict, "download_file"); if (pFunc_download == NULL || !PyCallable_Check(pFunc_download)) { throw std::runtime_error("Py can't reach the download function"); } // call a py file to deal those tasks PyObject *pyc_args = PyTuple_New(2); // parameters for python download PyObject *pssh_cfg = PyTuple_New(4); PyObject *ptask_list = PyList_New(tsize); init_ssh_params(pssh_cfg, thread_tasks->ssh_params); PyTuple_SetItem(pyc_args, 0, pssh_cfg); init_task_params(ptask_list, thread_tasks->task_buffer); PyTuple_SetItem(pyc_args, 1, ptask_list); PyObject *pRet = PyObject_CallObject(pFunc_download, pyc_args); dump_ret_msg(pRet); } catch(std::exception& e) { const char *err_msg = e.what(); int taskid; download_ret_t dr_ret; for (int i = 0; i < tsize; i++) { taskid = thread_tasks->task_buffer[i].task_id; dr_ret.ret_flag = -1; strncpy(dr_ret.err_msg, err_msg, NAME_LEN); task_ret_pool[taskid] = dr_ret; } } // TODO: comment this sentence print_map(); if (Py_Init_OK) { Py_Finalize(); } delete(thread_tasks); pthread_exit(NULL); }
MOD_INIT_DECL( pip$_vendor$requests$status_codes ) { #if defined(_NUITKA_EXE) || PYTHON_VERSION >= 300 static bool _init_done = false; // Modules might be imported repeatedly, which is to be ignored. if ( _init_done ) { return MOD_RETURN_VALUE( module_pip$_vendor$requests$status_codes ); } else { _init_done = true; } #endif #ifdef _NUITKA_MODULE // In case of a stand alone extension module, need to call initialization // the init here because that's the first and only time we are going to get // called here. // Initialize the constant values used. _initBuiltinModule(); createGlobalConstants(); // Initialize the compiled types of Nuitka. PyType_Ready( &Nuitka_Generator_Type ); PyType_Ready( &Nuitka_Function_Type ); PyType_Ready( &Nuitka_Method_Type ); PyType_Ready( &Nuitka_Frame_Type ); #if PYTHON_VERSION >= 350 PyType_Ready( &Nuitka_Coroutine_Type ); PyType_Ready( &Nuitka_CoroutineWrapper_Type ); #endif #if PYTHON_VERSION < 300 _initSlotCompare(); #endif #if PYTHON_VERSION >= 270 _initSlotIternext(); #endif patchBuiltinModule(); patchTypeComparison(); // Enable meta path based loader if not already done. setupMetaPathBasedLoader(); #if PYTHON_VERSION >= 300 patchInspectModule(); #endif #endif createModuleConstants(); createModuleCodeObjects(); // puts( "in initpip$_vendor$requests$status_codes" ); // Create the module object first. There are no methods initially, all are // added dynamically in actual code only. Also no "__doc__" is initially // set at this time, as it could not contain NUL characters this way, they // are instead set in early module code. No "self" for modules, we have no // use for it. #if PYTHON_VERSION < 300 module_pip$_vendor$requests$status_codes = Py_InitModule4( "pip._vendor.requests.status_codes", // Module Name NULL, // No methods initially, all are added // dynamically in actual module code only. NULL, // No __doc__ is initially set, as it could // not contain NUL this way, added early in // actual code. NULL, // No self for modules, we don't use it. PYTHON_API_VERSION ); #else module_pip$_vendor$requests$status_codes = PyModule_Create( &mdef_pip$_vendor$requests$status_codes ); #endif moduledict_pip$_vendor$requests$status_codes = (PyDictObject *)((PyModuleObject *)module_pip$_vendor$requests$status_codes)->md_dict; CHECK_OBJECT( module_pip$_vendor$requests$status_codes ); // Seems to work for Python2.7 out of the box, but for Python3, the module // doesn't automatically enter "sys.modules", so do it manually. #if PYTHON_VERSION >= 300 { int r = PyObject_SetItem( PySys_GetObject( (char *)"modules" ), const_str_digest_7407a472cb7f92da9dfbd02c8e685bfe, module_pip$_vendor$requests$status_codes ); assert( r != -1 ); } #endif // For deep importing of a module we need to have "__builtins__", so we set // it ourselves in the same way than CPython does. Note: This must be done // before the frame object is allocated, or else it may fail. PyObject *module_dict = PyModule_GetDict( module_pip$_vendor$requests$status_codes ); if ( PyDict_GetItem( module_dict, const_str_plain___builtins__ ) == NULL ) { PyObject *value = (PyObject *)builtin_module; // Check if main module, not a dict then. #if !defined(_NUITKA_EXE) || !0 value = PyModule_GetDict( value ); #endif #ifndef __NUITKA_NO_ASSERT__ int res = #endif PyDict_SetItem( module_dict, const_str_plain___builtins__, value ); assert( res == 0 ); } #if PYTHON_VERSION >= 330 PyDict_SetItem( module_dict, const_str_plain___loader__, metapath_based_loader ); #endif // Temp variables if any PyObject *tmp_for_loop_1__for_iterator = NULL; PyObject *tmp_for_loop_1__iter_value = NULL; PyObject *tmp_tuple_unpack_1__source_iter = NULL; PyObject *tmp_tuple_unpack_1__element_1 = NULL; PyObject *tmp_tuple_unpack_1__element_2 = NULL; PyObject *tmp_for_loop_2__for_iterator = NULL; PyObject *tmp_for_loop_2__iter_value = NULL; PyObject *exception_type = NULL, *exception_value = NULL; PyTracebackObject *exception_tb = NULL; NUITKA_MAY_BE_UNUSED int exception_lineno = -1; PyObject *exception_keeper_type_1; PyObject *exception_keeper_value_1; PyTracebackObject *exception_keeper_tb_1; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_1; PyObject *exception_keeper_type_2; PyObject *exception_keeper_value_2; PyTracebackObject *exception_keeper_tb_2; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_2; PyObject *exception_keeper_type_3; PyObject *exception_keeper_value_3; PyTracebackObject *exception_keeper_tb_3; NUITKA_MAY_BE_UNUSED int exception_keeper_lineno_3; PyObject *tmp_assign_source_1; PyObject *tmp_assign_source_2; PyObject *tmp_assign_source_3; PyObject *tmp_assign_source_4; PyObject *tmp_assign_source_5; PyObject *tmp_assign_source_6; PyObject *tmp_assign_source_7; PyObject *tmp_assign_source_8; PyObject *tmp_assign_source_9; PyObject *tmp_assign_source_10; PyObject *tmp_assign_source_11; PyObject *tmp_assign_source_12; PyObject *tmp_assign_source_13; PyObject *tmp_assign_source_14; PyObject *tmp_assign_source_15; PyObject *tmp_assign_source_16; PyObject *tmp_assign_source_17; PyObject *tmp_called_name_1; PyObject *tmp_called_name_2; PyObject *tmp_called_name_3; PyObject *tmp_called_name_4; int tmp_cond_truth_1; PyObject *tmp_cond_value_1; PyObject *tmp_import_globals_1; PyObject *tmp_import_name_from_1; PyObject *tmp_iter_arg_1; PyObject *tmp_iter_arg_2; PyObject *tmp_iter_arg_3; PyObject *tmp_iterator_attempt; PyObject *tmp_iterator_name_1; PyObject *tmp_kw_name_1; PyObject *tmp_next_source_1; PyObject *tmp_next_source_2; PyObject *tmp_setattr_attr_1; PyObject *tmp_setattr_attr_2; PyObject *tmp_setattr_target_1; PyObject *tmp_setattr_target_2; PyObject *tmp_setattr_value_1; PyObject *tmp_setattr_value_2; PyObject *tmp_source_name_1; PyObject *tmp_source_name_2; PyObject *tmp_source_name_3; PyObject *tmp_unpack_1; PyObject *tmp_unpack_2; NUITKA_MAY_BE_UNUSED PyObject *tmp_unused; PyFrameObject *frame_module; // Module code. tmp_assign_source_1 = Py_None; UPDATE_STRING_DICT0( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain___doc__, tmp_assign_source_1 ); tmp_assign_source_2 = const_str_digest_edc503ce8640402b515eac9b4be2e49c; UPDATE_STRING_DICT0( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain___file__, tmp_assign_source_2 ); tmp_assign_source_3 = Py_None; UPDATE_STRING_DICT0( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain___cached__, tmp_assign_source_3 ); tmp_assign_source_4 = const_str_digest_92068ee7fa29014ac06ffc664a1b4b4e; UPDATE_STRING_DICT0( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain___package__, tmp_assign_source_4 ); // Frame without reuse. frame_module = MAKE_MODULE_FRAME( codeobj_fc398c3ce42402f17822919035abca66, module_pip$_vendor$requests$status_codes ); // Push the new frame as the currently active one, and we should be exclusively // owning it. pushFrameStack( frame_module ); assert( Py_REFCNT( frame_module ) == 1 ); #if PYTHON_VERSION >= 340 frame_module->f_executing += 1; #endif // Framed code: tmp_import_globals_1 = ((PyModuleObject *)module_pip$_vendor$requests$status_codes)->md_dict; frame_module->f_lineno = 3; tmp_import_name_from_1 = IMPORT_MODULE( const_str_plain_structures, tmp_import_globals_1, tmp_import_globals_1, const_tuple_str_plain_LookupDict_tuple, const_int_pos_1 ); if ( tmp_import_name_from_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 3; goto frame_exception_exit_1; } tmp_assign_source_5 = IMPORT_NAME( tmp_import_name_from_1, const_str_plain_LookupDict ); Py_DECREF( tmp_import_name_from_1 ); if ( tmp_assign_source_5 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 3; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_LookupDict, tmp_assign_source_5 ); tmp_assign_source_6 = PyDict_Copy( const_dict_19730b058f28080932defca1165e072e ); UPDATE_STRING_DICT1( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain__codes, tmp_assign_source_6 ); tmp_called_name_1 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_LookupDict ); if (unlikely( tmp_called_name_1 == NULL )) { tmp_called_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_LookupDict ); } if ( tmp_called_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "LookupDict" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 84; goto frame_exception_exit_1; } tmp_kw_name_1 = PyDict_Copy( const_dict_38252060f20256dc080a28c7e1fb8512 ); frame_module->f_lineno = 84; tmp_assign_source_7 = CALL_FUNCTION_WITH_KEYARGS( tmp_called_name_1, tmp_kw_name_1 ); Py_DECREF( tmp_kw_name_1 ); if ( tmp_assign_source_7 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 84; goto frame_exception_exit_1; } UPDATE_STRING_DICT1( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes, tmp_assign_source_7 ); tmp_source_name_1 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain__codes ); if (unlikely( tmp_source_name_1 == NULL )) { tmp_source_name_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain__codes ); } if ( tmp_source_name_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "_codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 86; goto frame_exception_exit_1; } tmp_called_name_2 = LOOKUP_ATTRIBUTE( tmp_source_name_1, const_str_plain_items ); if ( tmp_called_name_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 86; goto frame_exception_exit_1; } frame_module->f_lineno = 86; tmp_iter_arg_1 = CALL_FUNCTION_NO_ARGS( tmp_called_name_2 ); Py_DECREF( tmp_called_name_2 ); if ( tmp_iter_arg_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 86; goto frame_exception_exit_1; } tmp_assign_source_8 = MAKE_ITERATOR( tmp_iter_arg_1 ); Py_DECREF( tmp_iter_arg_1 ); if ( tmp_assign_source_8 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 86; goto frame_exception_exit_1; } assert( tmp_for_loop_1__for_iterator == NULL ); tmp_for_loop_1__for_iterator = tmp_assign_source_8; // Tried code: loop_start_1:; tmp_next_source_1 = tmp_for_loop_1__for_iterator; tmp_assign_source_9 = ITERATOR_NEXT( tmp_next_source_1 ); if ( tmp_assign_source_9 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_1; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); frame_module->f_lineno = 86; goto try_except_handler_1; } } { PyObject *old = tmp_for_loop_1__iter_value; tmp_for_loop_1__iter_value = tmp_assign_source_9; Py_XDECREF( old ); } // Tried code: tmp_iter_arg_2 = tmp_for_loop_1__iter_value; tmp_assign_source_10 = MAKE_ITERATOR( tmp_iter_arg_2 ); if ( tmp_assign_source_10 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 86; goto try_except_handler_2; } { PyObject *old = tmp_tuple_unpack_1__source_iter; tmp_tuple_unpack_1__source_iter = tmp_assign_source_10; Py_XDECREF( old ); } tmp_unpack_1 = tmp_tuple_unpack_1__source_iter; tmp_assign_source_11 = UNPACK_NEXT( tmp_unpack_1, 0, 2 ); if ( tmp_assign_source_11 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } exception_lineno = 86; goto try_except_handler_2; } { PyObject *old = tmp_tuple_unpack_1__element_1; tmp_tuple_unpack_1__element_1 = tmp_assign_source_11; Py_XDECREF( old ); } tmp_unpack_2 = tmp_tuple_unpack_1__source_iter; tmp_assign_source_12 = UNPACK_NEXT( tmp_unpack_2, 1, 2 ); if ( tmp_assign_source_12 == NULL ) { if ( !ERROR_OCCURRED() ) { exception_type = PyExc_StopIteration; Py_INCREF( exception_type ); exception_value = NULL; exception_tb = NULL; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); } exception_lineno = 86; goto try_except_handler_2; } { PyObject *old = tmp_tuple_unpack_1__element_2; tmp_tuple_unpack_1__element_2 = tmp_assign_source_12; Py_XDECREF( old ); } tmp_iterator_name_1 = tmp_tuple_unpack_1__source_iter; // Check if iterator has left-over elements. CHECK_OBJECT( tmp_iterator_name_1 ); assert( HAS_ITERNEXT( tmp_iterator_name_1 ) ); tmp_iterator_attempt = (*Py_TYPE( tmp_iterator_name_1 )->tp_iternext)( tmp_iterator_name_1 ); if (likely( tmp_iterator_attempt == NULL )) { PyObject *error = GET_ERROR_OCCURRED(); if ( error != NULL ) { if ( EXCEPTION_MATCH_BOOL_SINGLE( error, PyExc_StopIteration )) { CLEAR_ERROR_OCCURRED(); } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); goto try_except_handler_2; } } } else { Py_DECREF( tmp_iterator_attempt ); // TODO: Could avoid PyErr_Format. #if PYTHON_VERSION < 300 PyErr_Format( PyExc_ValueError, "too many values to unpack" ); #else PyErr_Format( PyExc_ValueError, "too many values to unpack (expected 2)" ); #endif FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); goto try_except_handler_2; } goto try_end_1; // Exception handler code: try_except_handler_2:; exception_keeper_type_1 = exception_type; exception_keeper_value_1 = exception_value; exception_keeper_tb_1 = exception_tb; exception_keeper_lineno_1 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = -1; Py_XDECREF( tmp_tuple_unpack_1__source_iter ); tmp_tuple_unpack_1__source_iter = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_1 ); tmp_tuple_unpack_1__element_1 = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_2 ); tmp_tuple_unpack_1__element_2 = NULL; // Re-raise. exception_type = exception_keeper_type_1; exception_value = exception_keeper_value_1; exception_tb = exception_keeper_tb_1; exception_lineno = exception_keeper_lineno_1; goto try_except_handler_1; // End of try: try_end_1:; tmp_assign_source_13 = tmp_tuple_unpack_1__element_1; UPDATE_STRING_DICT0( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_code, tmp_assign_source_13 ); tmp_assign_source_14 = tmp_tuple_unpack_1__element_2; UPDATE_STRING_DICT0( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_titles, tmp_assign_source_14 ); CHECK_OBJECT( (PyObject *)tmp_tuple_unpack_1__source_iter ); Py_DECREF( tmp_tuple_unpack_1__source_iter ); tmp_tuple_unpack_1__source_iter = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_1 ); tmp_tuple_unpack_1__element_1 = NULL; Py_XDECREF( tmp_tuple_unpack_1__element_2 ); tmp_tuple_unpack_1__element_2 = NULL; tmp_iter_arg_3 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_titles ); if (unlikely( tmp_iter_arg_3 == NULL )) { tmp_iter_arg_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_titles ); } if ( tmp_iter_arg_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "titles" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 87; goto try_except_handler_1; } tmp_assign_source_15 = MAKE_ITERATOR( tmp_iter_arg_3 ); if ( tmp_assign_source_15 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_1; } { PyObject *old = tmp_for_loop_2__for_iterator; tmp_for_loop_2__for_iterator = tmp_assign_source_15; Py_XDECREF( old ); } // Tried code: loop_start_2:; tmp_next_source_2 = tmp_for_loop_2__for_iterator; tmp_assign_source_16 = ITERATOR_NEXT( tmp_next_source_2 ); if ( tmp_assign_source_16 == NULL ) { if ( CHECK_AND_CLEAR_STOP_ITERATION_OCCURRED() ) { goto loop_end_2; } else { FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); frame_module->f_lineno = 87; goto try_except_handler_3; } } { PyObject *old = tmp_for_loop_2__iter_value; tmp_for_loop_2__iter_value = tmp_assign_source_16; Py_XDECREF( old ); } tmp_assign_source_17 = tmp_for_loop_2__iter_value; UPDATE_STRING_DICT0( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_title, tmp_assign_source_17 ); tmp_setattr_target_1 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes ); if (unlikely( tmp_setattr_target_1 == NULL )) { tmp_setattr_target_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_codes ); } if ( tmp_setattr_target_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 88; goto try_except_handler_3; } tmp_setattr_attr_1 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_setattr_attr_1 == NULL )) { tmp_setattr_attr_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_setattr_attr_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 88; goto try_except_handler_3; } tmp_setattr_value_1 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_code ); if (unlikely( tmp_setattr_value_1 == NULL )) { tmp_setattr_value_1 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_code ); } if ( tmp_setattr_value_1 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "code" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 88; goto try_except_handler_3; } tmp_unused = BUILTIN_SETATTR( tmp_setattr_target_1, tmp_setattr_attr_1, tmp_setattr_value_1 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 88; goto try_except_handler_3; } tmp_source_name_2 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_source_name_2 == NULL )) { tmp_source_name_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_source_name_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 89; goto try_except_handler_3; } tmp_called_name_3 = LOOKUP_ATTRIBUTE( tmp_source_name_2, const_str_plain_startswith ); if ( tmp_called_name_3 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 89; goto try_except_handler_3; } frame_module->f_lineno = 89; tmp_cond_value_1 = CALL_FUNCTION_WITH_ARGS1( tmp_called_name_3, &PyTuple_GET_ITEM( const_tuple_str_chr_92_tuple, 0 ) ); Py_DECREF( tmp_called_name_3 ); if ( tmp_cond_value_1 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 89; goto try_except_handler_3; } tmp_cond_truth_1 = CHECK_IF_TRUE( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == -1 ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); Py_DECREF( tmp_cond_value_1 ); exception_lineno = 89; goto try_except_handler_3; } Py_DECREF( tmp_cond_value_1 ); if ( tmp_cond_truth_1 == 1 ) { goto branch_no_1; } else { goto branch_yes_1; } branch_yes_1:; tmp_setattr_target_2 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_codes ); if (unlikely( tmp_setattr_target_2 == NULL )) { tmp_setattr_target_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_codes ); } if ( tmp_setattr_target_2 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "codes" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 90; goto try_except_handler_3; } tmp_source_name_3 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_title ); if (unlikely( tmp_source_name_3 == NULL )) { tmp_source_name_3 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_title ); } if ( tmp_source_name_3 == NULL ) { exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "title" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 90; goto try_except_handler_3; } tmp_called_name_4 = LOOKUP_ATTRIBUTE( tmp_source_name_3, const_str_plain_upper ); if ( tmp_called_name_4 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 90; goto try_except_handler_3; } frame_module->f_lineno = 90; tmp_setattr_attr_2 = CALL_FUNCTION_NO_ARGS( tmp_called_name_4 ); Py_DECREF( tmp_called_name_4 ); if ( tmp_setattr_attr_2 == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 90; goto try_except_handler_3; } tmp_setattr_value_2 = GET_STRING_DICT_VALUE( moduledict_pip$_vendor$requests$status_codes, (Nuitka_StringObject *)const_str_plain_code ); if (unlikely( tmp_setattr_value_2 == NULL )) { tmp_setattr_value_2 = GET_STRING_DICT_VALUE( dict_builtin, (Nuitka_StringObject *)const_str_plain_code ); } if ( tmp_setattr_value_2 == NULL ) { Py_DECREF( tmp_setattr_attr_2 ); exception_type = PyExc_NameError; Py_INCREF( exception_type ); exception_value = PyUnicode_FromFormat( "name '%s' is not defined", "code" ); exception_tb = NULL; NORMALIZE_EXCEPTION( &exception_type, &exception_value, &exception_tb ); CHAIN_EXCEPTION( exception_value ); exception_lineno = 90; goto try_except_handler_3; } tmp_unused = BUILTIN_SETATTR( tmp_setattr_target_2, tmp_setattr_attr_2, tmp_setattr_value_2 ); Py_DECREF( tmp_setattr_attr_2 ); if ( tmp_unused == NULL ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 90; goto try_except_handler_3; } branch_no_1:; if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 87; goto try_except_handler_3; } goto loop_start_2; loop_end_2:; goto try_end_2; // Exception handler code: try_except_handler_3:; exception_keeper_type_2 = exception_type; exception_keeper_value_2 = exception_value; exception_keeper_tb_2 = exception_tb; exception_keeper_lineno_2 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = -1; Py_XDECREF( tmp_for_loop_2__iter_value ); tmp_for_loop_2__iter_value = NULL; Py_XDECREF( tmp_for_loop_2__for_iterator ); tmp_for_loop_2__for_iterator = NULL; // Re-raise. exception_type = exception_keeper_type_2; exception_value = exception_keeper_value_2; exception_tb = exception_keeper_tb_2; exception_lineno = exception_keeper_lineno_2; goto try_except_handler_1; // End of try: try_end_2:; Py_XDECREF( tmp_for_loop_2__iter_value ); tmp_for_loop_2__iter_value = NULL; Py_XDECREF( tmp_for_loop_2__for_iterator ); tmp_for_loop_2__for_iterator = NULL; if ( CONSIDER_THREADING() == false ) { assert( ERROR_OCCURRED() ); FETCH_ERROR_OCCURRED( &exception_type, &exception_value, &exception_tb ); exception_lineno = 86; goto try_except_handler_1; } goto loop_start_1; loop_end_1:; goto try_end_3; // Exception handler code: try_except_handler_1:; exception_keeper_type_3 = exception_type; exception_keeper_value_3 = exception_value; exception_keeper_tb_3 = exception_tb; exception_keeper_lineno_3 = exception_lineno; exception_type = NULL; exception_value = NULL; exception_tb = NULL; exception_lineno = -1; Py_XDECREF( tmp_for_loop_1__iter_value ); tmp_for_loop_1__iter_value = NULL; Py_XDECREF( tmp_for_loop_1__for_iterator ); tmp_for_loop_1__for_iterator = NULL; // Re-raise. exception_type = exception_keeper_type_3; exception_value = exception_keeper_value_3; exception_tb = exception_keeper_tb_3; exception_lineno = exception_keeper_lineno_3; goto frame_exception_exit_1; // End of try: try_end_3:; // Restore frame exception if necessary. #if 0 RESTORE_FRAME_EXCEPTION( frame_module ); #endif popFrameStack(); assertFrameObject( frame_module ); Py_DECREF( frame_module ); goto frame_no_exception_1; frame_exception_exit_1:; #if 0 RESTORE_FRAME_EXCEPTION( frame_module ); #endif if ( exception_tb == NULL ) { exception_tb = MAKE_TRACEBACK( frame_module, exception_lineno ); } else if ( exception_tb->tb_frame != frame_module ) { PyTracebackObject *traceback_new = MAKE_TRACEBACK( frame_module, exception_lineno ); traceback_new->tb_next = exception_tb; exception_tb = traceback_new; } // Put the previous frame back on top. popFrameStack(); #if PYTHON_VERSION >= 340 frame_module->f_executing -= 1; #endif Py_DECREF( frame_module ); // Return the error. goto module_exception_exit; frame_no_exception_1:; Py_XDECREF( tmp_for_loop_1__iter_value ); tmp_for_loop_1__iter_value = NULL; Py_XDECREF( tmp_for_loop_1__for_iterator ); tmp_for_loop_1__for_iterator = NULL; return MOD_RETURN_VALUE( module_pip$_vendor$requests$status_codes ); module_exception_exit: RESTORE_ERROR_OCCURRED( exception_type, exception_value, exception_tb ); return MOD_RETURN_VALUE( NULL ); }
/* Shared python2/3 module initialization: */ static int initModule(PyObject *m) { PyObject * d; /* * treat error to register rpm cleanup hook as fatal, tracebacks * can and will leave stale locks around if we can't clean up */ if (Py_AtExit(rpm_exithook) == -1) return 0; /* failure to initialize rpm (crypto and all) is rather fatal too... */ if (rpmReadConfigFiles(NULL, NULL) == -1) return 0; d = PyModule_GetDict(m); pyrpmError = PyErr_NewException("_rpm.error", NULL, NULL); if (pyrpmError != NULL) PyDict_SetItemString(d, "error", pyrpmError); Py_INCREF(&hdr_Type); PyModule_AddObject(m, "hdr", (PyObject *) &hdr_Type); Py_INCREF(&rpmarchive_Type); PyModule_AddObject(m, "archive", (PyObject *) &rpmarchive_Type); Py_INCREF(&rpmds_Type); PyModule_AddObject(m, "ds", (PyObject *) &rpmds_Type); Py_INCREF(&rpmfd_Type); PyModule_AddObject(m, "fd", (PyObject *) &rpmfd_Type); Py_INCREF(&rpmfi_Type); PyModule_AddObject(m, "fi", (PyObject *) &rpmfi_Type); Py_INCREF(&rpmfile_Type); PyModule_AddObject(m, "file", (PyObject *) &rpmfile_Type); Py_INCREF(&rpmfiles_Type); PyModule_AddObject(m, "files", (PyObject *) &rpmfiles_Type); Py_INCREF(&rpmKeyring_Type); PyModule_AddObject(m, "keyring", (PyObject *) &rpmKeyring_Type); Py_INCREF(&rpmmi_Type); PyModule_AddObject(m, "mi", (PyObject *) &rpmmi_Type); Py_INCREF(&rpmii_Type); PyModule_AddObject(m, "ii", (PyObject *) &rpmii_Type); Py_INCREF(&rpmProblem_Type); PyModule_AddObject(m, "prob", (PyObject *) &rpmProblem_Type); Py_INCREF(&rpmPubkey_Type); PyModule_AddObject(m, "pubkey", (PyObject *) &rpmPubkey_Type); Py_INCREF(&rpmstrPool_Type); PyModule_AddObject(m, "strpool", (PyObject *) &rpmstrPool_Type); #if 0 Py_INCREF(&rpmtd_Type); PyModule_AddObject(m, "td", (PyObject *) &rpmtd_Type); #endif Py_INCREF(&rpmte_Type); PyModule_AddObject(m, "te", (PyObject *) &rpmte_Type); Py_INCREF(&rpmts_Type); PyModule_AddObject(m, "ts", (PyObject *) &rpmts_Type); addRpmTags(m); PyModule_AddStringConstant(m, "__version__", RPMVERSION); #define REGISTER_ENUM(val) PyModule_AddIntConstant(m, #val, val) REGISTER_ENUM(RPMTAG_NOT_FOUND); REGISTER_ENUM(RPMRC_OK); REGISTER_ENUM(RPMRC_NOTFOUND); REGISTER_ENUM(RPMRC_FAIL); REGISTER_ENUM(RPMRC_NOTTRUSTED); REGISTER_ENUM(RPMRC_NOKEY); REGISTER_ENUM(RPMFILE_STATE_NORMAL); REGISTER_ENUM(RPMFILE_STATE_REPLACED); REGISTER_ENUM(RPMFILE_STATE_NOTINSTALLED); REGISTER_ENUM(RPMFILE_STATE_NETSHARED); REGISTER_ENUM(RPMFILE_STATE_WRONGCOLOR); REGISTER_ENUM(RPMFILE_CONFIG); REGISTER_ENUM(RPMFILE_DOC); REGISTER_ENUM(RPMFILE_ICON); REGISTER_ENUM(RPMFILE_MISSINGOK); REGISTER_ENUM(RPMFILE_NOREPLACE); REGISTER_ENUM(RPMFILE_SPECFILE); REGISTER_ENUM(RPMFILE_GHOST); REGISTER_ENUM(RPMFILE_LICENSE); REGISTER_ENUM(RPMFILE_README); REGISTER_ENUM(RPMFILE_PUBKEY); REGISTER_ENUM(RPMDEP_SENSE_REQUIRES); REGISTER_ENUM(RPMDEP_SENSE_CONFLICTS); REGISTER_ENUM(RPMSENSE_ANY); REGISTER_ENUM(RPMSENSE_LESS); REGISTER_ENUM(RPMSENSE_GREATER); REGISTER_ENUM(RPMSENSE_EQUAL); REGISTER_ENUM(RPMSENSE_POSTTRANS); REGISTER_ENUM(RPMSENSE_PREREQ); REGISTER_ENUM(RPMSENSE_PRETRANS); REGISTER_ENUM(RPMSENSE_INTERP); REGISTER_ENUM(RPMSENSE_SCRIPT_PRE); REGISTER_ENUM(RPMSENSE_SCRIPT_POST); REGISTER_ENUM(RPMSENSE_SCRIPT_PREUN); REGISTER_ENUM(RPMSENSE_SCRIPT_POSTUN); REGISTER_ENUM(RPMSENSE_SCRIPT_VERIFY); REGISTER_ENUM(RPMSENSE_FIND_REQUIRES); REGISTER_ENUM(RPMSENSE_FIND_PROVIDES); REGISTER_ENUM(RPMSENSE_TRIGGERIN); REGISTER_ENUM(RPMSENSE_TRIGGERUN); REGISTER_ENUM(RPMSENSE_TRIGGERPOSTUN); REGISTER_ENUM(RPMSENSE_RPMLIB); REGISTER_ENUM(RPMSENSE_TRIGGERPREIN); REGISTER_ENUM(RPMSENSE_KEYRING); REGISTER_ENUM(RPMSENSE_CONFIG); REGISTER_ENUM(RPMTRANS_FLAG_TEST); REGISTER_ENUM(RPMTRANS_FLAG_BUILD_PROBS); REGISTER_ENUM(RPMTRANS_FLAG_NOSCRIPTS); REGISTER_ENUM(RPMTRANS_FLAG_JUSTDB); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERS); REGISTER_ENUM(RPMTRANS_FLAG_NODOCS); REGISTER_ENUM(RPMTRANS_FLAG_ALLFILES); REGISTER_ENUM(RPMTRANS_FLAG_KEEPOBSOLETE); REGISTER_ENUM(RPMTRANS_FLAG_NOCONTEXTS); REGISTER_ENUM(RPMTRANS_FLAG_REPACKAGE); REGISTER_ENUM(RPMTRANS_FLAG_REVERSE); REGISTER_ENUM(RPMTRANS_FLAG_NOPRE); REGISTER_ENUM(RPMTRANS_FLAG_NOPOST); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERPREIN); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERIN); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERUN); REGISTER_ENUM(RPMTRANS_FLAG_NOPREUN); REGISTER_ENUM(RPMTRANS_FLAG_NOPOSTUN); REGISTER_ENUM(RPMTRANS_FLAG_NOTRIGGERPOSTUN); REGISTER_ENUM(RPMTRANS_FLAG_NOPRETRANS); REGISTER_ENUM(RPMTRANS_FLAG_NOPOSTTRANS); REGISTER_ENUM(RPMTRANS_FLAG_NOMD5); REGISTER_ENUM(RPMTRANS_FLAG_NOFILEDIGEST); REGISTER_ENUM(RPMTRANS_FLAG_NOSUGGEST); REGISTER_ENUM(RPMTRANS_FLAG_ADDINDEPS); REGISTER_ENUM(RPMTRANS_FLAG_NOCONFIGS); REGISTER_ENUM(RPMPROB_FILTER_IGNOREOS); REGISTER_ENUM(RPMPROB_FILTER_IGNOREARCH); REGISTER_ENUM(RPMPROB_FILTER_REPLACEPKG); REGISTER_ENUM(RPMPROB_FILTER_FORCERELOCATE); REGISTER_ENUM(RPMPROB_FILTER_REPLACENEWFILES); REGISTER_ENUM(RPMPROB_FILTER_REPLACEOLDFILES); REGISTER_ENUM(RPMPROB_FILTER_OLDPACKAGE); REGISTER_ENUM(RPMPROB_FILTER_DISKSPACE); REGISTER_ENUM(RPMPROB_FILTER_DISKNODES); REGISTER_ENUM(RPMCALLBACK_UNKNOWN); REGISTER_ENUM(RPMCALLBACK_INST_PROGRESS); REGISTER_ENUM(RPMCALLBACK_INST_START); REGISTER_ENUM(RPMCALLBACK_INST_OPEN_FILE); REGISTER_ENUM(RPMCALLBACK_INST_CLOSE_FILE); REGISTER_ENUM(RPMCALLBACK_TRANS_PROGRESS); REGISTER_ENUM(RPMCALLBACK_TRANS_START); REGISTER_ENUM(RPMCALLBACK_TRANS_STOP); REGISTER_ENUM(RPMCALLBACK_UNINST_PROGRESS); REGISTER_ENUM(RPMCALLBACK_UNINST_START); REGISTER_ENUM(RPMCALLBACK_UNINST_STOP); REGISTER_ENUM(RPMCALLBACK_REPACKAGE_PROGRESS); REGISTER_ENUM(RPMCALLBACK_REPACKAGE_START); REGISTER_ENUM(RPMCALLBACK_REPACKAGE_STOP); REGISTER_ENUM(RPMCALLBACK_UNPACK_ERROR); REGISTER_ENUM(RPMCALLBACK_CPIO_ERROR); REGISTER_ENUM(RPMCALLBACK_SCRIPT_ERROR); REGISTER_ENUM(RPMCALLBACK_SCRIPT_START); REGISTER_ENUM(RPMCALLBACK_SCRIPT_STOP); REGISTER_ENUM(RPMCALLBACK_INST_STOP); REGISTER_ENUM(RPMPROB_BADARCH); REGISTER_ENUM(RPMPROB_BADOS); REGISTER_ENUM(RPMPROB_PKG_INSTALLED); REGISTER_ENUM(RPMPROB_BADRELOCATE); REGISTER_ENUM(RPMPROB_REQUIRES); REGISTER_ENUM(RPMPROB_CONFLICT); REGISTER_ENUM(RPMPROB_NEW_FILE_CONFLICT); REGISTER_ENUM(RPMPROB_FILE_CONFLICT); REGISTER_ENUM(RPMPROB_OLDPACKAGE); REGISTER_ENUM(RPMPROB_DISKSPACE); REGISTER_ENUM(RPMPROB_DISKNODES); REGISTER_ENUM(RPMPROB_OBSOLETES); REGISTER_ENUM(VERIFY_DIGEST); REGISTER_ENUM(VERIFY_SIGNATURE); REGISTER_ENUM(RPMLOG_EMERG); REGISTER_ENUM(RPMLOG_ALERT); REGISTER_ENUM(RPMLOG_CRIT); REGISTER_ENUM(RPMLOG_ERR); REGISTER_ENUM(RPMLOG_WARNING); REGISTER_ENUM(RPMLOG_NOTICE); REGISTER_ENUM(RPMLOG_INFO); REGISTER_ENUM(RPMLOG_DEBUG); REGISTER_ENUM(RPMMIRE_DEFAULT); REGISTER_ENUM(RPMMIRE_STRCMP); REGISTER_ENUM(RPMMIRE_REGEX); REGISTER_ENUM(RPMMIRE_GLOB); REGISTER_ENUM(RPMVSF_DEFAULT); REGISTER_ENUM(RPMVSF_NOHDRCHK); REGISTER_ENUM(RPMVSF_NEEDPAYLOAD); REGISTER_ENUM(RPMVSF_NOSHA1HEADER); REGISTER_ENUM(RPMVSF_NOMD5HEADER); REGISTER_ENUM(RPMVSF_NODSAHEADER); REGISTER_ENUM(RPMVSF_NORSAHEADER); REGISTER_ENUM(RPMVSF_NOSHA1); REGISTER_ENUM(RPMVSF_NOMD5); REGISTER_ENUM(RPMVSF_NODSA); REGISTER_ENUM(RPMVSF_NORSA); REGISTER_ENUM(_RPMVSF_NODIGESTS); REGISTER_ENUM(_RPMVSF_NOSIGNATURES); REGISTER_ENUM(_RPMVSF_NOHEADER); REGISTER_ENUM(_RPMVSF_NOPAYLOAD); REGISTER_ENUM(TR_ADDED); REGISTER_ENUM(TR_REMOVED); REGISTER_ENUM(RPMDBI_PACKAGES); REGISTER_ENUM(RPMDBI_LABEL); REGISTER_ENUM(RPMDBI_INSTFILENAMES); REGISTER_ENUM(RPMDBI_NAME); REGISTER_ENUM(RPMDBI_BASENAMES); REGISTER_ENUM(RPMDBI_GROUP); REGISTER_ENUM(RPMDBI_REQUIRENAME); REGISTER_ENUM(RPMDBI_PROVIDENAME); REGISTER_ENUM(RPMDBI_CONFLICTNAME); REGISTER_ENUM(RPMDBI_OBSOLETENAME); REGISTER_ENUM(RPMDBI_TRIGGERNAME); REGISTER_ENUM(RPMDBI_DIRNAMES); REGISTER_ENUM(RPMDBI_INSTALLTID); REGISTER_ENUM(RPMDBI_SIGMD5); REGISTER_ENUM(RPMDBI_SHA1HEADER); REGISTER_ENUM(HEADERCONV_EXPANDFILELIST); REGISTER_ENUM(HEADERCONV_COMPRESSFILELIST); REGISTER_ENUM(HEADERCONV_RETROFIT_V3); return 1; }
static void gplp_load_base (GOPluginLoader *loader, GOErrorInfo **ret_error) { static gchar const *python_file_extensions[] = {"py", "pyc", "pyo", NULL}; GnmPythonPluginLoader *loader_python = GNM_PYTHON_PLUGIN_LOADER (loader); gchar const **file_ext; GnmPython *py_object; GnmPyInterpreter *py_interpreter_info; gchar *full_module_file_name = NULL; FILE *f; GOPlugin *plugin = go_plugin_loader_get_plugin (loader); GOErrorInfo *open_error = NULL; PyObject *modules, *main_module, *main_module_dict; GO_INIT_RET_ERROR_INFO (ret_error); g_object_set_data (G_OBJECT (plugin), "python-loader", loader); py_object = gnm_python_object_get (ret_error); if (py_object == NULL) return; /* gnm_python_object_get sets ret_error */ py_interpreter_info = gnm_python_new_interpreter (py_object, plugin); if (py_interpreter_info == NULL) { *ret_error = go_error_info_new_str (_("Cannot create new Python interpreter.")); gnm_python_clear_error_if_needed (py_object); g_object_unref (py_object); return; } for (file_ext = python_file_extensions; *file_ext != NULL; file_ext++) { gchar *file_name = g_strconcat ( loader_python->module_name, ".", *file_ext, NULL); gchar *path = g_build_filename ( go_plugin_get_dir_name (plugin), file_name, NULL); g_free (file_name); if (g_file_test (path, G_FILE_TEST_EXISTS)) { full_module_file_name = path; break; } else g_free (path); } if (full_module_file_name == NULL) { *ret_error = go_error_info_new_printf ( _("Module \"%s\" doesn't exist."), loader_python->module_name); gnm_python_destroy_interpreter (py_object, py_interpreter_info); g_object_unref (py_object); return; } f = gnumeric_fopen_error_info (full_module_file_name, "r", &open_error); g_free (full_module_file_name); if (f == NULL) { *ret_error = open_error; gnm_python_destroy_interpreter (py_object, py_interpreter_info); g_object_unref (py_object); return; } if (PyRun_SimpleFile (f, loader_python->module_name) != 0) { (void) fclose (f); *ret_error = go_error_info_new_printf ( _("Execution of module \"%s\" failed."), loader_python->module_name); gnm_python_destroy_interpreter (py_object, py_interpreter_info); g_object_unref (py_object); return; } (void) fclose (f); modules = PyImport_GetModuleDict (); g_return_if_fail (modules != NULL); main_module = PyDict_GetItemString (modules, (char *) "__main__"); g_return_if_fail (main_module != NULL); main_module_dict = PyModule_GetDict (main_module); g_return_if_fail (main_module_dict != NULL); loader_python->py_object = py_object; loader_python->py_interpreter_info = py_interpreter_info; loader_python->main_module = main_module; loader_python->main_module_dict = main_module_dict; }
PyMODINIT_FUNC initwarpC(void) #endif #endif { PyObject *m, *d; /* PyObject *pystdout; */ PyObject *date; #if PY_MAJOR_VERSION >= 3 m = PyModule_Create(&moduledef); #else #ifdef MPIPARALLEL m = Py_InitModule("warpCparallel", warpC_methods); #else m = Py_InitModule("warpC", warpC_methods); #endif #endif d = PyModule_GetDict(m); #ifdef MPIPARALLEL ErrorObject = PyErr_NewException("warpCparallel.error",NULL,NULL); #else ErrorObject = PyErr_NewException("warpC.error",NULL,NULL); #endif PyDict_SetItemString(d, "error", ErrorObject); date = PyUnicode_FromString(GITORIGINDATE); PyDict_SetItemString(d, "origindate", date); Py_XDECREF(date); date = PyUnicode_FromString(GITLOCALDATE); PyDict_SetItemString(d, "localdate", date); Py_XDECREF(date); date = PyUnicode_FromString(GITCOMMITHASH); PyDict_SetItemString(d, "commithash", date); Py_XDECREF(date); if (PyErr_Occurred()) Py_FatalError("can not initialize module warpC"); /* pystdout = PySys_GetObject("stdout"); */ /* PyFile_WriteString("Forthon edition\n",pystdout); */ import_array(); #if PY_MAJOR_VERSION < 3 inittoppy(); initenvpy(); initw3dpy(); initf3dpy(); initwxypy(); initfxypy(); initwrzpy(); initfrzpy(); initcirpy(); initherpy(); initchopy(); initem2dpy(); initem3dpy(); #endif #if PY_MAJOR_VERSION >= 3 return m; #else return; #endif }
int init_uwsgi_app(int loader, void *arg1, struct wsgi_request *wsgi_req, PyThreadState *interpreter, int app_type) { PyObject *app_list = NULL, *applications = NULL; int id = uwsgi_apps_cnt; int multiapp = 0; int i; struct uwsgi_app *wi; time_t now = uwsgi_now(); if (uwsgi_get_app_id(wsgi_req->appid, wsgi_req->appid_len, -1) != -1) { uwsgi_log( "mountpoint %.*s already configured. skip.\n", wsgi_req->appid_len, wsgi_req->appid); return -1; } wi = &uwsgi_apps[id]; memset(wi, 0, sizeof(struct uwsgi_app)); wi->mountpoint_len = wsgi_req->appid_len < 0xff ? wsgi_req->appid_len : (0xff-1); strncpy(wi->mountpoint, wsgi_req->appid, wi->mountpoint_len); // dynamic chdir ? if (wsgi_req->chdir_len > 0) { strncpy(wi->chdir, wsgi_req->chdir, wsgi_req->chdir_len < 0xff ? wsgi_req->chdir_len : (0xff-1)); #ifdef UWSGI_DEBUG uwsgi_debug("chdir to %s\n", wi->chdir); #endif if (chdir(wi->chdir)) { uwsgi_error("chdir()"); } } // Initialize a new environment for the new interpreter // reload "os" environ to allow dynamic setenv() if (up.reload_os_env) { char **e, *p; PyObject *k, *env_value; PyObject *os_module = PyImport_ImportModule("os"); if (os_module) { PyObject *os_module_dict = PyModule_GetDict(os_module); PyObject *py_environ = PyDict_GetItemString(os_module_dict, "environ"); if (py_environ) { for (e = environ; *e != NULL; e++) { p = strchr(*e, '='); if (p == NULL) continue; k = PyString_FromStringAndSize(*e, (int)(p-*e)); if (k == NULL) { PyErr_Print(); continue; } env_value = PyString_FromString(p+1); if (env_value == NULL) { PyErr_Print(); Py_DECREF(k); continue; } #ifdef UWSGI_DEBUG uwsgi_log("%s = %s\n", PyString_AsString(k), PyString_AsString(env_value)); #endif if (PyObject_SetItem(py_environ, k, env_value)) { PyErr_Print(); } Py_DECREF(k); Py_DECREF(env_value); } } } } #ifdef UWSGI_MINTERPRETERS if (interpreter == NULL && id) { wi->interpreter = Py_NewInterpreter(); if (!wi->interpreter) { uwsgi_log( "unable to initialize the new python interpreter\n"); exit(1); } PyThreadState_Swap(wi->interpreter); init_pyargv(); #ifdef UWSGI_EMBEDDED // we need to inizialize an embedded module for every interpreter init_uwsgi_embedded_module(); #endif init_uwsgi_vars(); } else if (interpreter) { wi->interpreter = interpreter; } else { wi->interpreter = up.main_thread; } if (wsgi_req->pyhome_len) { set_dyn_pyhome(wsgi_req->pyhome, wsgi_req->pyhome_len); } #else wi->interpreter = up.main_thread; #endif if (wsgi_req->touch_reload_len > 0 && wsgi_req->touch_reload_len < 0xff) { struct stat trst; strncpy(wi->touch_reload, wsgi_req->touch_reload, wsgi_req->touch_reload_len); if (!stat(wi->touch_reload, &trst)) { wi->touch_reload_mtime = trst.st_mtime; } } wi->callable = up.loaders[loader](arg1); if (!wi->callable) { uwsgi_log("unable to load app %d (mountpoint='%s') (callable not found or import error)\n", id, wi->mountpoint); goto doh; } // the module contains multiple apps if (PyDict_Check((PyObject *)wi->callable)) { applications = wi->callable; uwsgi_log("found a multiapp module...\n"); app_list = PyDict_Keys(applications); multiapp = PyList_Size(app_list); if (multiapp < 1) { uwsgi_log("you have to define at least one app in the apllications dictionary\n"); goto doh; } PyObject *app_mnt = PyList_GetItem(app_list, 0); if (!PyString_Check(app_mnt)) { uwsgi_log("the app mountpoint must be a string\n"); goto doh; } char *tmp_mountpoint = PyString_AsString(app_mnt); wi->mountpoint_len = strlen(wi->mountpoint) < 0xff ? strlen(wi->mountpoint) : (0xff-1); strncpy(wi->mountpoint, tmp_mountpoint, wi->mountpoint_len); wsgi_req->appid = wi->mountpoint; wsgi_req->appid_len = wi->mountpoint_len; #ifdef UWSGI_DEBUG uwsgi_log("main mountpoint = %s\n", wi->mountpoint); #endif wi->callable = PyDict_GetItem(applications, app_mnt); if (PyString_Check((PyObject *) wi->callable)) { PyObject *callables_dict = get_uwsgi_pydict((char *)arg1); if (callables_dict) { wi->callable = PyDict_GetItem(callables_dict, (PyObject *)wi->callable); } } } Py_INCREF((PyObject *)wi->callable); #ifdef UWSGI_ASYNC wi->environ = malloc(sizeof(PyObject*)*uwsgi.cores); if (!wi->environ) { uwsgi_error("malloc()"); exit(1); } for(i=0;i<uwsgi.cores;i++) { wi->environ[i] = PyDict_New(); if (!wi->environ[i]) { uwsgi_log("unable to allocate new env dictionary for app\n"); exit(1); } } #else wi->environ = PyDict_New(); if (!wi->environ) { uwsgi_log("unable to allocate new env dictionary for app\n"); exit(1); } #endif wi->argc = 1; if (app_type == PYTHON_APP_TYPE_WSGI) { #ifdef UWSGI_DEBUG uwsgi_log("-- WSGI callable selected --\n"); #endif wi->request_subhandler = uwsgi_request_subhandler_wsgi; wi->response_subhandler = uwsgi_response_subhandler_wsgi; wi->argc = 2; } else if (app_type == PYTHON_APP_TYPE_WEB3) { #ifdef UWSGI_DEBUG uwsgi_log("-- Web3 callable selected --\n"); #endif wi->request_subhandler = uwsgi_request_subhandler_web3; wi->response_subhandler = uwsgi_response_subhandler_web3; } else if (app_type == PYTHON_APP_TYPE_PUMP) { #ifdef UWSGI_DEBUG uwsgi_log("-- Pump callable selected --\n"); #endif wi->request_subhandler = uwsgi_request_subhandler_pump; wi->response_subhandler = uwsgi_response_subhandler_pump; } #ifdef UWSGI_ASYNC wi->args = malloc(sizeof(PyObject*)*uwsgi.cores); if (!wi->args) { uwsgi_error("malloc()"); exit(1); } for(i=0;i<uwsgi.cores;i++) { wi->args[i] = PyTuple_New(wi->argc); if (!wi->args[i]) { uwsgi_log("unable to allocate new tuple for app args\n"); exit(1); } // add start_response on WSGI app Py_INCREF((PyObject *)up.wsgi_spitout); if (app_type == PYTHON_APP_TYPE_WSGI) { if (PyTuple_SetItem(wi->args[i], 1, up.wsgi_spitout)) { uwsgi_log("unable to set start_response in args tuple\n"); exit(1); } } } #else // add start_response on WSGI app Py_INCREF((PyObject *)up.wsgi_spitout); wi->args = PyTuple_New(wi->argc); if (app_type == PYTHON_APP_TYPE_WSGI) { if (PyTuple_SetItem(wi->args, 1, up.wsgi_spitout)) { uwsgi_log("unable to set start_response in args tuple\n"); exit(1); } } #endif if (app_type == PYTHON_APP_TYPE_WSGI) { #ifdef UWSGI_SENDFILE // prepare sendfile() for WSGI app wi->sendfile = PyCFunction_New(uwsgi_sendfile_method, NULL); #endif #ifdef UWSGI_ASYNC wi->eventfd_read = PyCFunction_New(uwsgi_eventfd_read_method, NULL); wi->eventfd_write = PyCFunction_New(uwsgi_eventfd_write_method, NULL); #endif } // cache most used values wi->gateway_version = PyTuple_New(2); PyTuple_SetItem(wi->gateway_version, 0, PyInt_FromLong(1)); PyTuple_SetItem(wi->gateway_version, 1, PyInt_FromLong(0)); Py_INCREF((PyObject *)wi->gateway_version); wi->uwsgi_version = PyString_FromString(UWSGI_VERSION); Py_INCREF((PyObject *)wi->uwsgi_version); wi->uwsgi_node = PyString_FromString(uwsgi.hostname); Py_INCREF((PyObject *)wi->uwsgi_node); if (uwsgi.threads > 1 && id) { // if we have multiple threads we need to initialize a PyThreadState for each one for(i=0;i<uwsgi.threads;i++) { //uwsgi_log("%p\n", uwsgi.core[i]->ts[id]); uwsgi.core[i]->ts[id] = PyThreadState_New( ((PyThreadState *)wi->interpreter)->interp); if (!uwsgi.core[i]->ts[id]) { uwsgi_log("unable to allocate new PyThreadState structure for app %s", wi->mountpoint); goto doh; } } PyThreadState_Swap((PyThreadState *) pthread_getspecific(up.upt_save_key) ); } else if (interpreter == NULL && id) { PyThreadState_Swap(up.main_thread); } const char *default_app = ""; if ((wsgi_req->appid_len == 0 || (wsgi_req->appid_len = 1 && wsgi_req->appid[0] == '/')) && uwsgi.default_app == -1) { default_app = " (default app)" ; uwsgi.default_app = id; } wi->started_at = now; wi->startup_time = uwsgi_now() - now; if (app_type == PYTHON_APP_TYPE_WSGI) { uwsgi_log( "WSGI app %d (mountpoint='%.*s') ready in %d seconds on interpreter %p pid: %d%s\n", id, wi->mountpoint_len, wi->mountpoint, (int) wi->startup_time, wi->interpreter, (int) getpid(), default_app); } else if (app_type == PYTHON_APP_TYPE_WEB3) { uwsgi_log( "Web3 app %d (mountpoint='%.*s') ready in %d seconds on interpreter %p pid: %d%s\n", id, wi->mountpoint_len, wi->mountpoint, (int) wi->startup_time, wi->interpreter, (int) getpid(), default_app); } else if (app_type == PYTHON_APP_TYPE_PUMP) { uwsgi_log( "Pump app %d (mountpoint='%.*s') ready in %d seconds on interpreter %p pid: %d%s\n", id, wi->mountpoint_len, wi->mountpoint, (int) wi->startup_time, wi->interpreter, (int) getpid(), default_app); } uwsgi_apps_cnt++; if (multiapp > 1) { for(i=1;i<multiapp;i++) { PyObject *app_mnt = PyList_GetItem(app_list, i); if (!PyString_Check(app_mnt)) { uwsgi_log("applications dictionary key must be a string, skipping.\n"); continue; } wsgi_req->appid = PyString_AsString(app_mnt); wsgi_req->appid_len = strlen(wsgi_req->appid); PyObject *a_callable = PyDict_GetItem(applications, app_mnt); if (PyString_Check(a_callable)) { PyObject *callables_dict = get_uwsgi_pydict((char *)arg1); if (callables_dict) { a_callable = PyDict_GetItem(callables_dict, a_callable); } } if (!a_callable) { uwsgi_log("skipping broken app %s\n", wsgi_req->appid); continue; } init_uwsgi_app(LOADER_CALLABLE, a_callable, wsgi_req, wi->interpreter, app_type); } } // emulate COW uwsgi_emulate_cow_for_apps(id); return id; doh: if (PyErr_Occurred()) PyErr_Print(); #ifdef UWSGI_MINTERPRETERS if (interpreter == NULL && id) { Py_EndInterpreter(wi->interpreter); if (uwsgi.threads > 1) { PyThreadState_Swap((PyThreadState *) pthread_getspecific(up.upt_save_key)); } else { PyThreadState_Swap(up.main_thread); } } #endif return -1; }
void init_uwsgi_vars() { PyObject *pysys, *pysys_dict, *pypath; PyObject *modules = PyImport_GetModuleDict(); PyObject *tmp_module; /* add cwd to pythonpath */ pysys = PyImport_ImportModule("sys"); if (!pysys) { PyErr_Print(); exit(1); } pysys_dict = PyModule_GetDict(pysys); #ifdef PYTHREE // fix stdout and stderr PyObject *new_stdprint = PyFile_NewStdPrinter(2); PyDict_SetItemString(pysys_dict, "stdout", new_stdprint); PyDict_SetItemString(pysys_dict, "__stdout__", new_stdprint); PyDict_SetItemString(pysys_dict, "stderr", new_stdprint); PyDict_SetItemString(pysys_dict, "__stderr__", new_stdprint); #endif pypath = PyDict_GetItemString(pysys_dict, "path"); if (!pypath) { PyErr_Print(); exit(1); } if (PyList_Insert(pypath, 0, UWSGI_PYFROMSTRING(".")) != 0) { PyErr_Print(); } struct uwsgi_string_list *uppp = up.python_path; while(uppp) { if (PyList_Insert(pypath, 0, UWSGI_PYFROMSTRING(uppp->value)) != 0) { PyErr_Print(); } else { uwsgi_log("added %s to pythonpath.\n", uppp->value); } uppp = uppp->next; } struct uwsgi_string_list *uppma = up.pymodule_alias; while(uppma) { // split key=value char *value = strchr(uppma->value, '='); if (!value) { uwsgi_log("invalid pymodule-alias syntax\n"); goto next; } value[0] = 0; if (!strchr(value + 1, '/')) { // this is a standard pymodule tmp_module = PyImport_ImportModule(value + 1); if (!tmp_module) { PyErr_Print(); exit(1); } PyDict_SetItemString(modules, uppma->value, tmp_module); } else { // this is a filepath that need to be mapped tmp_module = uwsgi_pyimport_by_filename(uppma->value, value + 1); if (!tmp_module) { PyErr_Print(); exit(1); } } uwsgi_log("mapped virtual pymodule \"%s\" to real pymodule \"%s\"\n", uppma->value, value + 1); // reset original value value[0] = '='; next: uppma = uppma->next; } }
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(); }
void init_uwsgi_embedded_module() { PyObject *new_uwsgi_module, *zero; int i; PyType_Ready(&uwsgi_InputType); /* initialize for stats */ up.workers_tuple = PyTuple_New(uwsgi.numproc); for (i = 0; i < uwsgi.numproc; i++) { zero = PyDict_New(); Py_INCREF(zero); PyTuple_SetItem(up.workers_tuple, i, zero); } #ifdef PYTHREE PyImport_AppendInittab("uwsgi", init_uwsgi3); new_uwsgi_module = PyImport_AddModule("uwsgi"); #else new_uwsgi_module = Py_InitModule3("uwsgi", NULL, uwsgi_py_doc); #endif if (new_uwsgi_module == NULL) { uwsgi_log("could not initialize the uwsgi python module\n"); exit(1); } Py_INCREF((PyObject *) &uwsgi_InputType); up.embedded_dict = PyModule_GetDict(new_uwsgi_module); if (!up.embedded_dict) { uwsgi_log("could not get uwsgi module __dict__\n"); exit(1); } // just for safety Py_INCREF(up.embedded_dict); if (PyDict_SetItemString(up.embedded_dict, "version", PyString_FromString(UWSGI_VERSION))) { PyErr_Print(); exit(1); } PyObject *uwsgi_py_version_info = PyTuple_New(5); PyTuple_SetItem(uwsgi_py_version_info, 0, PyInt_FromLong(UWSGI_VERSION_BASE)); PyTuple_SetItem(uwsgi_py_version_info, 1, PyInt_FromLong(UWSGI_VERSION_MAJOR)); PyTuple_SetItem(uwsgi_py_version_info, 2, PyInt_FromLong(UWSGI_VERSION_MINOR)); PyTuple_SetItem(uwsgi_py_version_info, 3, PyInt_FromLong(UWSGI_VERSION_REVISION)); PyTuple_SetItem(uwsgi_py_version_info, 4, PyString_FromString(UWSGI_VERSION_CUSTOM)); if (PyDict_SetItemString(up.embedded_dict, "version_info", uwsgi_py_version_info)) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "hostname", PyString_FromStringAndSize(uwsgi.hostname, uwsgi.hostname_len))) { PyErr_Print(); exit(1); } if (uwsgi.mode) { if (PyDict_SetItemString(up.embedded_dict, "mode", PyString_FromString(uwsgi.mode))) { PyErr_Print(); exit(1); } } if (uwsgi.pidfile) { if (PyDict_SetItemString(up.embedded_dict, "pidfile", PyString_FromString(uwsgi.pidfile))) { PyErr_Print(); exit(1); } } #ifdef UWSGI_SPOOLER if (uwsgi.spoolers) { int sc = 0; struct uwsgi_spooler *uspool = uwsgi.spoolers; while(uspool) { sc++; uspool = uspool->next;} PyObject *py_spooler_tuple = PyTuple_New(sc); uspool = uwsgi.spoolers; sc = 0; while(uspool) { PyTuple_SetItem(py_spooler_tuple, sc, PyString_FromString(uspool->dir)); sc++; uspool = uspool->next; } if (PyDict_SetItemString(up.embedded_dict, "spoolers", py_spooler_tuple)) { PyErr_Print(); exit(1); } } #endif if (PyDict_SetItemString(up.embedded_dict, "SPOOL_RETRY", PyInt_FromLong(-1))) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "SPOOL_OK", PyInt_FromLong(-2))) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "SPOOL_IGNORE", PyInt_FromLong(0))) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "numproc", PyInt_FromLong(uwsgi.numproc))) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "has_threads", PyInt_FromLong(uwsgi.has_threads))) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "cores", PyInt_FromLong(uwsgi.cores))) { PyErr_Print(); exit(1); } if (uwsgi.loop) { if (PyDict_SetItemString(up.embedded_dict, "loop", PyString_FromString(uwsgi.loop))) { PyErr_Print(); exit(1); } } else { PyDict_SetItemString(up.embedded_dict, "loop", Py_None); } PyObject *py_opt_dict = PyDict_New(); for (i = 0; i < uwsgi.exported_opts_cnt; i++) { if (PyDict_Contains(py_opt_dict, PyString_FromString(uwsgi.exported_opts[i]->key))) { PyObject *py_opt_item = PyDict_GetItemString(py_opt_dict, uwsgi.exported_opts[i]->key); if (PyList_Check(py_opt_item)) { if (uwsgi.exported_opts[i]->value == NULL) { PyList_Append(py_opt_item, Py_True); } else { PyList_Append(py_opt_item, PyString_FromString(uwsgi.exported_opts[i]->value)); } } else { PyObject *py_opt_list = PyList_New(0); PyList_Append(py_opt_list, py_opt_item); if (uwsgi.exported_opts[i]->value == NULL) { PyList_Append(py_opt_list, Py_True); } else { PyList_Append(py_opt_list, PyString_FromString(uwsgi.exported_opts[i]->value)); } PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, py_opt_list); } } else { if (uwsgi.exported_opts[i]->value == NULL) { PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, Py_True); } else { PyDict_SetItemString(py_opt_dict, uwsgi.exported_opts[i]->key, PyString_FromString(uwsgi.exported_opts[i]->value)); } } } if (PyDict_SetItemString(up.embedded_dict, "opt", py_opt_dict)) { PyErr_Print(); exit(1); } PyObject *py_magic_table = PyDict_New(); uint8_t mtk; for (i = 0; i <= 0xff; i++) { // a bit of magic :P mtk = i; if (uwsgi.magic_table[i]) { if (uwsgi.magic_table[i][0] != 0) { PyDict_SetItem(py_magic_table, PyString_FromStringAndSize((char *) &mtk, 1), PyString_FromString(uwsgi.magic_table[i])); } } } if (PyDict_SetItemString(up.embedded_dict, "magic_table", py_magic_table)) { PyErr_Print(); exit(1); } #ifdef UNBIT if (PyDict_SetItemString(up.embedded_dict, "unbit", Py_True)) { #else if (PyDict_SetItemString(up.embedded_dict, "unbit", Py_None)) { #endif PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "buffer_size", PyInt_FromLong(uwsgi.buffer_size))) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "started_on", PyInt_FromLong(uwsgi.start_tv.tv_sec))) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "start_response", up.wsgi_spitout)) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "applications", Py_None)) { PyErr_Print(); exit(1); } if (uwsgi.is_a_reload) { if (PyDict_SetItemString(up.embedded_dict, "is_a_reload", Py_True)) { PyErr_Print(); exit(1); } } else { if (PyDict_SetItemString(up.embedded_dict, "is_a_reload", Py_False)) { PyErr_Print(); exit(1); } } up.embedded_args = PyTuple_New(2); if (!up.embedded_args) { PyErr_Print(); exit(1); } if (PyDict_SetItemString(up.embedded_dict, "message_manager_marshal", Py_None)) { PyErr_Print(); exit(1); } init_uwsgi_module_advanced(new_uwsgi_module); #ifdef UWSGI_SPOOLER if (uwsgi.spoolers) { init_uwsgi_module_spooler(new_uwsgi_module); } #endif if (uwsgi.sharedareasize > 0 && uwsgi.sharedarea) { init_uwsgi_module_sharedarea(new_uwsgi_module); } if (uwsgi.cache_max_items > 0) { init_uwsgi_module_cache(new_uwsgi_module); } if (uwsgi.queue_size > 0) { init_uwsgi_module_queue(new_uwsgi_module); } #ifdef UWSGI_SNMP if (uwsgi.snmp) { init_uwsgi_module_snmp(new_uwsgi_module); } #endif if (up.extension) { up.extension(); } } #endif int uwsgi_python_magic(char *mountpoint, char *lazy) { char *qc = strchr(lazy, ':'); if (qc) { qc[0] = 0; up.callable = qc + 1; } if (!strcmp(lazy + strlen(lazy) - 3, ".py")) { up.file_config = lazy; return 1; } else if (!strcmp(lazy + strlen(lazy) - 5, ".wsgi")) { up.file_config = lazy; return 1; } else if (qc && strchr(lazy, '.')) { up.wsgi_config = lazy; return 1; } // reset lazy if (qc) { qc[0] = ':'; } return 0; }
PyThreadState * Py_NewInterpreter(void) { PyInterpreterState *interp; PyThreadState *tstate, *save_tstate; PyObject *bimod, *sysmod; if (!initialized) Py_FatalError("Py_NewInterpreter: call Py_Initialize first"); #ifdef WITH_THREAD /* Issue #10915, #15751: The GIL API doesn't work with multiple interpreters: disable PyGILState_Check(). */ _PyGILState_check_enabled = 0; #endif interp = PyInterpreterState_New(); if (interp == NULL) return NULL; tstate = PyThreadState_New(interp); if (tstate == NULL) { PyInterpreterState_Delete(interp); return NULL; } save_tstate = PyThreadState_Swap(tstate); /* XXX The following is lax in error checking */ interp->modules = PyDict_New(); bimod = _PyImport_FindBuiltin("builtins"); if (bimod != NULL) { interp->builtins = PyModule_GetDict(bimod); if (interp->builtins == NULL) goto handle_error; Py_INCREF(interp->builtins); } /* initialize builtin exceptions */ _PyExc_Init(bimod); sysmod = _PyImport_FindBuiltin("sys"); if (bimod != NULL && sysmod != NULL) { PyObject *pstderr; interp->sysdict = PyModule_GetDict(sysmod); if (interp->sysdict == NULL) goto handle_error; Py_INCREF(interp->sysdict); PySys_SetPath(Py_GetPath()); PyDict_SetItemString(interp->sysdict, "modules", interp->modules); /* Set up a preliminary stderr printer until we have enough infrastructure for the io module in place. */ pstderr = PyFile_NewStdPrinter(fileno(stderr)); if (pstderr == NULL) Py_FatalError("Py_Initialize: can't set preliminary stderr"); _PySys_SetObjectId(&PyId_stderr, pstderr); PySys_SetObject("__stderr__", pstderr); Py_DECREF(pstderr); _PyImportHooks_Init(); import_init(interp, sysmod); if (initfsencoding(interp) < 0) goto handle_error; if (initstdio() < 0) Py_FatalError( "Py_Initialize: can't initialize sys standard streams"); initmain(interp); if (!Py_NoSiteFlag) initsite(); } if (!PyErr_Occurred()) return tstate; handle_error: /* Oops, it didn't work. Undo it all. */ PyErr_PrintEx(0); PyThreadState_Clear(tstate); PyThreadState_Swap(save_tstate); PyThreadState_Delete(tstate); PyInterpreterState_Delete(interp); return NULL; }
/* The item is a borrowed reference. */ static const char * get_filter(PyObject *category, PyObject *text, Py_ssize_t lineno, PyObject *module, PyObject **item) { PyObject *action, *m, *d; Py_ssize_t i; PyObject *warnings_filters; warnings_filters = get_warnings_attr("filters"); if (warnings_filters == NULL) { if (PyErr_Occurred()) return NULL; } else { Py_DECREF(_filters); _filters = warnings_filters; } if (!PyList_Check(_filters)) { PyErr_SetString(PyExc_ValueError, MODULE_NAME ".filters must be a list"); return NULL; } /* _filters could change while we are iterating over it. */ for (i = 0; i < PyList_GET_SIZE(_filters); i++) { PyObject *tmp_item, *action, *msg, *cat, *mod, *ln_obj; Py_ssize_t ln; int is_subclass, good_msg, good_mod; tmp_item = *item = PyList_GET_ITEM(_filters, i); if (PyTuple_Size(tmp_item) != 5) { PyErr_Format(PyExc_ValueError, MODULE_NAME ".filters item %zd isn't a 5-tuple", i); return NULL; } /* Python code: action, msg, cat, mod, ln = item */ action = PyTuple_GET_ITEM(tmp_item, 0); msg = PyTuple_GET_ITEM(tmp_item, 1); cat = PyTuple_GET_ITEM(tmp_item, 2); mod = PyTuple_GET_ITEM(tmp_item, 3); ln_obj = PyTuple_GET_ITEM(tmp_item, 4); good_msg = check_matched(msg, text); good_mod = check_matched(mod, module); is_subclass = PyObject_IsSubclass(category, cat); ln = PyInt_AsSsize_t(ln_obj); if (good_msg == -1 || good_mod == -1 || is_subclass == -1 || (ln == -1 && PyErr_Occurred())) return NULL; if (good_msg && is_subclass && good_mod && (ln == 0 || lineno == ln)) return PyString_AsString(action); } m = PyImport_ImportModule(MODULE_NAME); if (m == NULL) return NULL; d = PyModule_GetDict(m); Py_DECREF(m); if (d == NULL) return NULL; action = PyDict_GetItemString(d, DEFAULT_ACTION_NAME); if (action != NULL) return PyString_AsString(action); PyErr_SetString(PyExc_ValueError, MODULE_NAME "." DEFAULT_ACTION_NAME " not found"); return NULL; }
static void pyt_exec_str(RESULT * result, const char *module, const char *function, int argc, const char *argv[]) { PyObject *pName, *pModule, *pDict, *pFunc; PyObject *pArgs, *pValue; const char *rv = NULL; int i; pName = PyString_FromString(module); /* Error checking of pName left out */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pDict = PyModule_GetDict(pModule); /* pDict is a borrowed reference */ pFunc = PyDict_GetItemString(pDict, function); /* pFun: Borrowed reference */ if (pFunc && PyCallable_Check(pFunc)) { pArgs = PyTuple_New(argc); for (i = 0; i < argc; ++i) { pValue = PyString_FromString(argv[i]); if (!pValue) { Py_DECREF(pArgs); Py_DECREF(pModule); error("Cannot convert argument \"%s\" to python format", argv[i]); SetResult(&result, R_STRING, ""); return; } /* pValue reference stolen here: */ PyTuple_SetItem(pArgs, i, pValue); } pValue = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pValue != NULL) { rv = PyString_AsString(pValue); SetResult(&result, R_STRING, rv); Py_DECREF(pValue); /* rv is now a 'dangling reference' */ return; } else { Py_DECREF(pModule); error("Python call failed (\"%s.%s\")", module, function); /* print traceback on stderr */ PyErr_PrintEx(0); SetResult(&result, R_STRING, ""); return; } /* pDict and pFunc are borrowed and must not be Py_DECREF-ed */ } else { error("Can not find python function \"%s.%s\"", module, function); } Py_DECREF(pModule); } else { error("Failed to load python module \"%s\"", module); /* print traceback on stderr */ PyErr_PrintEx(0); } SetResult(&result, R_STRING, ""); return; }
static PyObject* module_init(void) { PyObject *module, *mod_dict, *interfaces, *conflicterr; #ifdef KEY_TYPE_IS_PYOBJECT object_ = PyTuple_GetItem(Py_TYPE(Py_None)->tp_bases, 0); if (object_ == NULL) return NULL; #endif sort_str = INTERN("sort"); if (!sort_str) return NULL; reverse_str = INTERN("reverse"); if (!reverse_str) return NULL; __setstate___str = INTERN("__setstate__"); if (!__setstate___str) return NULL; _bucket_type_str = INTERN("_bucket_type"); if (!_bucket_type_str) return NULL; /* Grab the ConflictError class */ interfaces = PyImport_ImportModule("BTrees.Interfaces"); if (interfaces != NULL) { conflicterr = PyObject_GetAttrString(interfaces, "BTreesConflictError"); if (conflicterr != NULL) ConflictError = conflicterr; Py_DECREF(interfaces); } if (ConflictError == NULL) { Py_INCREF(PyExc_ValueError); ConflictError=PyExc_ValueError; } /* Initialize the PyPersist_C_API and the type objects. */ #ifdef PY3K cPersistenceCAPI = (cPersistenceCAPIstruct *)PyCapsule_Import( "persistent.cPersistence.CAPI", 0); #else cPersistenceCAPI = (cPersistenceCAPIstruct *)PyCObject_Import( "persistent.cPersistence", "CAPI"); #endif if (cPersistenceCAPI == NULL) return NULL; #ifdef PY3K #define _SET_TYPE(typ) ((PyObject*)(&typ))->ob_type = &PyType_Type #else #define _SET_TYPE(typ) (typ).ob_type = &PyType_Type #endif _SET_TYPE(BTreeItemsType); _SET_TYPE(BTreeIter_Type); BTreeIter_Type.tp_getattro = PyObject_GenericGetAttr; BucketType.tp_new = PyType_GenericNew; SetType.tp_new = PyType_GenericNew; BTreeType.tp_new = PyType_GenericNew; TreeSetType.tp_new = PyType_GenericNew; if (!init_persist_type(&BucketType)) return NULL; if (!init_persist_type(&BTreeType)) return NULL; if (!init_persist_type(&SetType)) return NULL; if (!init_persist_type(&TreeSetType)) return NULL; if (PyDict_SetItem(BTreeType.tp_dict, _bucket_type_str, (PyObject *)&BucketType) < 0) { fprintf(stderr, "btree failed\n"); return NULL; } if (PyDict_SetItem(TreeSetType.tp_dict, _bucket_type_str, (PyObject *)&SetType) < 0) { fprintf(stderr, "bucket failed\n"); return NULL; } /* Create the module and add the functions */ #ifdef PY3K module = PyModule_Create(&moduledef); #else module = Py_InitModule4("_" MOD_NAME_PREFIX "BTree", module_methods, BTree_module_documentation, (PyObject *)NULL, PYTHON_API_VERSION); #endif /* Add some symbolic constants to the module */ mod_dict = PyModule_GetDict(module); if (PyDict_SetItemString(mod_dict, MOD_NAME_PREFIX "Bucket", (PyObject *)&BucketType) < 0) return NULL; if (PyDict_SetItemString(mod_dict, MOD_NAME_PREFIX "BTree", (PyObject *)&BTreeType) < 0) return NULL; if (PyDict_SetItemString(mod_dict, MOD_NAME_PREFIX "Set", (PyObject *)&SetType) < 0) return NULL; if (PyDict_SetItemString(mod_dict, MOD_NAME_PREFIX "TreeSet", (PyObject *)&TreeSetType) < 0) return NULL; if (PyDict_SetItemString(mod_dict, MOD_NAME_PREFIX "TreeIterator", (PyObject *)&BTreeIter_Type) < 0) return NULL; /* We also want to be able to access these constants without the prefix * so that code can more easily exchange modules (particularly the integer * and long modules, but also others). The TreeIterator is only internal, * so we don't bother to expose that. */ if (PyDict_SetItemString(mod_dict, "Bucket", (PyObject *)&BucketType) < 0) return NULL; if (PyDict_SetItemString(mod_dict, "BTree", (PyObject *)&BTreeType) < 0) return NULL; if (PyDict_SetItemString(mod_dict, "Set", (PyObject *)&SetType) < 0) return NULL; if (PyDict_SetItemString(mod_dict, "TreeSet", (PyObject *)&TreeSetType) < 0) return NULL; #if defined(ZODB_64BIT_INTS) && defined(NEED_LONG_LONG_SUPPORT) if (PyDict_SetItemString(mod_dict, "using64bits", Py_True) < 0) return NULL; #else if (PyDict_SetItemString(mod_dict, "using64bits", Py_False) < 0) return NULL; #endif return module; }
PyObject * PyModule_Create2(struct PyModuleDef* module, int module_api_version) { PyObject *d, *v, *n; PyMethodDef *ml; const char* name; PyModuleObject *m; if (!Py_IsInitialized()) Py_FatalError("Interpreter not initialized (version mismatch?)"); if (PyType_Ready(&moduledef_type) < 0) return NULL; if (module->m_base.m_index == 0) { max_module_number++; Py_REFCNT(module) = 1; Py_TYPE(module) = &moduledef_type; module->m_base.m_index = max_module_number; } name = module->m_name; if (module_api_version != PYTHON_API_VERSION) { char message[512]; PyOS_snprintf(message, sizeof(message), api_version_warning, name, PYTHON_API_VERSION, name, module_api_version); if (PyErr_WarnEx(PyExc_RuntimeWarning, message, 1)) return NULL; } /* Make sure name is fully qualified. This is a bit of a hack: when the shared library is loaded, the module name is "package.module", but the module calls PyModule_Create*() with just "module" for the name. The shared library loader squirrels away the true name of the module in _Py_PackageContext, and PyModule_Create*() will substitute this (if the name actually matches). */ if (_Py_PackageContext != NULL) { char *p = strrchr(_Py_PackageContext, '.'); if (p != NULL && strcmp(module->m_name, p+1) == 0) { name = _Py_PackageContext; _Py_PackageContext = NULL; } } if ((m = (PyModuleObject*)PyModule_New(name)) == NULL) return NULL; if (module->m_size > 0) { m->md_state = PyMem_MALLOC(module->m_size); if (!m->md_state) { PyErr_NoMemory(); Py_DECREF(m); return NULL; } memset(m->md_state, 0, module->m_size); } d = PyModule_GetDict((PyObject*)m); if (module->m_methods != NULL) { n = PyUnicode_FromString(name); if (n == NULL) return NULL; for (ml = module->m_methods; ml->ml_name != NULL; ml++) { if ((ml->ml_flags & METH_CLASS) || (ml->ml_flags & METH_STATIC)) { PyErr_SetString(PyExc_ValueError, "module functions cannot set" " METH_CLASS or METH_STATIC"); Py_DECREF(n); return NULL; } v = PyCFunction_NewEx(ml, (PyObject*)m, n); if (v == NULL) { Py_DECREF(n); return NULL; } if (PyDict_SetItemString(d, ml->ml_name, v) != 0) { Py_DECREF(v); Py_DECREF(n); return NULL; } Py_DECREF(v); } Py_DECREF(n); } if (module->m_doc != NULL) { v = PyUnicode_FromString(module->m_doc); if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) { Py_XDECREF(v); return NULL; } Py_DECREF(v); } m->md_def = module; return (PyObject*)m; }
void ThreadProc( void *data ) { PyObject *pName, *pModule, *pDict, *pFunc; PyThreadState *mainThreadState, *myThreadState, *tempState; PyInterpreterState *mainInterpreterState; CMD_LINE_STRUCT* arg = (CMD_LINE_STRUCT*)data; // Initialize python inerpreter Py_Initialize(); // Initialize thread support PyEval_InitThreads(); // Save a pointer to the main PyThreadState object mainThreadState = PyThreadState_Get(); // Get a reference to the PyInterpreterState mainInterpreterState = mainThreadState->interp; // Create a thread state object for this thread myThreadState = PyThreadState_New(mainInterpreterState); // Release global lock PyEval_ReleaseLock(); // Acquire global lock PyEval_AcquireLock(); // Swap in my thread state tempState = PyThreadState_Swap(myThreadState); // Now execute some python code (call python functions) pName = PyString_FromString(arg->argv[1]); pModule = PyImport_Import(pName); // pDict and pFunc are borrowed references pDict = PyModule_GetDict(pModule); pFunc = PyDict_GetItemString(pDict, arg->argv[2]); if (PyCallable_Check(pFunc)) { PyObject_CallObject(pFunc, NULL); } else { PyErr_Print(); } // Clean up Py_DECREF(pModule); Py_DECREF(pName); // Swap out the current thread PyThreadState_Swap(tempState); // Release global lock PyEval_ReleaseLock(); // Clean up thread state PyThreadState_Clear(myThreadState); PyThreadState_Delete(myThreadState); Py_Finalize(); printf("My thread is finishing...\n"); // Exiting the thread #ifdef WIN32 // Windows code _endthread(); #else // POSIX code pthread_exit(NULL); #endif }
PyMODINIT_FUNC init_locale(void) { PyObject *m, *d, *x; #ifdef HAVE_LANGINFO_H int i; #endif m = Py_InitModule("_locale", PyLocale_Methods); if (m == NULL) return; d = PyModule_GetDict(m); x = PyInt_FromLong(LC_CTYPE); PyDict_SetItemString(d, "LC_CTYPE", x); Py_XDECREF(x); x = PyInt_FromLong(LC_TIME); PyDict_SetItemString(d, "LC_TIME", x); Py_XDECREF(x); x = PyInt_FromLong(LC_COLLATE); PyDict_SetItemString(d, "LC_COLLATE", x); Py_XDECREF(x); x = PyInt_FromLong(LC_MONETARY); PyDict_SetItemString(d, "LC_MONETARY", x); Py_XDECREF(x); #ifdef LC_MESSAGES x = PyInt_FromLong(LC_MESSAGES); PyDict_SetItemString(d, "LC_MESSAGES", x); Py_XDECREF(x); #endif /* LC_MESSAGES */ x = PyInt_FromLong(LC_NUMERIC); PyDict_SetItemString(d, "LC_NUMERIC", x); Py_XDECREF(x); x = PyInt_FromLong(LC_ALL); PyDict_SetItemString(d, "LC_ALL", x); Py_XDECREF(x); x = PyInt_FromLong(CHAR_MAX); PyDict_SetItemString(d, "CHAR_MAX", x); Py_XDECREF(x); Error = PyErr_NewException("locale.Error", NULL, NULL); PyDict_SetItemString(d, "Error", Error); x = PyString_FromString(locale__doc__); PyDict_SetItemString(d, "__doc__", x); Py_XDECREF(x); #ifdef HAVE_LANGINFO_H for (i = 0; langinfo_constants[i].name; i++) { PyModule_AddIntConstant(m, langinfo_constants[i].name, langinfo_constants[i].value); } #endif }
PyObject *uwsgi_paste_loader(void *arg1) { char *paste = (char *) arg1; PyObject *paste_module, *paste_dict, *paste_loadapp; PyObject *paste_arg, *paste_app; uwsgi_log( "Loading paste environment: %s\n", paste); if (up.paste_logger) { PyObject *paste_logger_dict = get_uwsgi_pydict("paste.script.util.logging_config"); if (paste_logger_dict) { PyObject *paste_logger_fileConfig = PyDict_GetItemString(paste_logger_dict, "fileConfig"); if (paste_logger_fileConfig) { PyObject *paste_logger_arg = PyTuple_New(1); if (!paste_logger_arg) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } PyTuple_SetItem(paste_logger_arg, 0, PyString_FromString(paste+7)); if (python_call(paste_logger_fileConfig, paste_logger_arg, 0, NULL)) { PyErr_Print(); } } } } paste_module = PyImport_ImportModule("paste.deploy"); if (!paste_module) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } paste_dict = PyModule_GetDict(paste_module); if (!paste_dict) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } paste_loadapp = PyDict_GetItemString(paste_dict, "loadapp"); if (!paste_loadapp) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } paste_arg = PyTuple_New(1); if (!paste_arg) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } if (PyTuple_SetItem(paste_arg, 0, PyString_FromString(paste))) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } paste_app = PyEval_CallObject(paste_loadapp, paste_arg); if (!paste_app) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } return paste_app; }
PyMODINIT_FUNC init_sqlite3(void) { PyObject *module, *dict; PyObject *tmp_obj; int i; module = Py_InitModule("_sqlite3", module_methods); if (!module || (row_setup_types() < 0) || (cursor_setup_types() < 0) || (connection_setup_types() < 0) || (cache_setup_types() < 0) || (statement_setup_types() < 0) || (prepare_protocol_setup_types() < 0) ) { return; } Py_INCREF(&ConnectionType); PyModule_AddObject(module, "Connection", (PyObject*) &ConnectionType); Py_INCREF(&CursorType); PyModule_AddObject(module, "Cursor", (PyObject*) &CursorType); Py_INCREF(&CacheType); PyModule_AddObject(module, "Statement", (PyObject*)&StatementType); Py_INCREF(&StatementType); PyModule_AddObject(module, "Cache", (PyObject*) &CacheType); Py_INCREF(&SQLitePrepareProtocolType); PyModule_AddObject(module, "PrepareProtocol", (PyObject*) &SQLitePrepareProtocolType); Py_INCREF(&RowType); PyModule_AddObject(module, "Row", (PyObject*) &RowType); if (!(dict = PyModule_GetDict(module))) { goto error; } /*** Create DB-API Exception hierarchy */ if (!(Error = PyErr_NewException(MODULE_NAME ".Error", PyExc_StandardError, NULL))) { goto error; } PyDict_SetItemString(dict, "Error", Error); if (!(Warning = PyErr_NewException(MODULE_NAME ".Warning", PyExc_StandardError, NULL))) { goto error; } PyDict_SetItemString(dict, "Warning", Warning); /* Error subclasses */ if (!(InterfaceError = PyErr_NewException(MODULE_NAME ".InterfaceError", Error, NULL))) { goto error; } PyDict_SetItemString(dict, "InterfaceError", InterfaceError); if (!(DatabaseError = PyErr_NewException(MODULE_NAME ".DatabaseError", Error, NULL))) { goto error; } PyDict_SetItemString(dict, "DatabaseError", DatabaseError); /* DatabaseError subclasses */ if (!(InternalError = PyErr_NewException(MODULE_NAME ".InternalError", DatabaseError, NULL))) { goto error; } PyDict_SetItemString(dict, "InternalError", InternalError); if (!(OperationalError = PyErr_NewException(MODULE_NAME ".OperationalError", DatabaseError, NULL))) { goto error; } PyDict_SetItemString(dict, "OperationalError", OperationalError); if (!(ProgrammingError = PyErr_NewException(MODULE_NAME ".ProgrammingError", DatabaseError, NULL))) { goto error; } PyDict_SetItemString(dict, "ProgrammingError", ProgrammingError); if (!(IntegrityError = PyErr_NewException(MODULE_NAME ".IntegrityError", DatabaseError,NULL))) { goto error; } PyDict_SetItemString(dict, "IntegrityError", IntegrityError); if (!(DataError = PyErr_NewException(MODULE_NAME ".DataError", DatabaseError, NULL))) { goto error; } PyDict_SetItemString(dict, "DataError", DataError); if (!(NotSupportedError = PyErr_NewException(MODULE_NAME ".NotSupportedError", DatabaseError, NULL))) { goto error; } PyDict_SetItemString(dict, "NotSupportedError", NotSupportedError); /* We just need "something" unique for OptimizedUnicode. It does not really * need to be a string subclass. Just anything that can act as a special * marker for us. So I pulled PyCell_Type out of my magic hat. */ Py_INCREF((PyObject*)&PyCell_Type); OptimizedUnicode = (PyObject*)&PyCell_Type; PyDict_SetItemString(dict, "OptimizedUnicode", OptimizedUnicode); /* Set integer constants */ for (i = 0; _int_constants[i].constant_name != 0; i++) { tmp_obj = PyInt_FromLong(_int_constants[i].constant_value); if (!tmp_obj) { goto error; } PyDict_SetItemString(dict, _int_constants[i].constant_name, tmp_obj); Py_DECREF(tmp_obj); } if (!(tmp_obj = PyString_FromString(PYSQLITE_VERSION))) { goto error; } PyDict_SetItemString(dict, "version", tmp_obj); Py_DECREF(tmp_obj); if (!(tmp_obj = PyString_FromString(sqlite3_libversion()))) { goto error; } PyDict_SetItemString(dict, "sqlite_version", tmp_obj); Py_DECREF(tmp_obj); /* initialize microprotocols layer */ microprotocols_init(dict); /* initialize the default converters */ converters_init(dict); _enable_callback_tracebacks = 0; /* Original comment form _bsddb.c in the Python core. This is also still * needed nowadays for Python 2.3/2.4. * * PyEval_InitThreads is called here due to a quirk in python 1.5 * - 2.2.1 (at least) according to Russell Williamson <*****@*****.**>: * The global interepreter lock is not initialized until the first * thread is created using thread.start_new_thread() or fork() is * called. that would cause the ALLOW_THREADS here to segfault due * to a null pointer reference if no threads or child processes * have been created. This works around that and is a no-op if * threads have already been initialized. * (see pybsddb-users mailing list post on 2002-08-07) */ PyEval_InitThreads(); error: if (PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, MODULE_NAME ": init failed"); } }
PyObject *uwsgi_eval_loader(void *arg1) { #ifdef UWSGI_PYPY uwsgi_log("the eval loader is currently not supported under PyPy !!!\n"); return NULL; #else char *code = (char *) arg1; PyObject *wsgi_eval_module, *wsgi_eval_callable = NULL; struct _node *wsgi_eval_node = NULL; PyObject *wsgi_compiled_node; wsgi_eval_node = PyParser_SimpleParseString(code, Py_file_input); if (!wsgi_eval_node) { PyErr_Print(); uwsgi_log( "failed to parse <eval> code\n"); exit(UWSGI_FAILED_APP_CODE); } wsgi_compiled_node = (PyObject *) PyNode_Compile(wsgi_eval_node, "uwsgi_eval_config"); if (!wsgi_compiled_node) { PyErr_Print(); uwsgi_log( "failed to compile eval code\n"); exit(UWSGI_FAILED_APP_CODE); } wsgi_eval_module = PyImport_ExecCodeModule("uwsgi_eval_config", wsgi_compiled_node); if (!wsgi_eval_module) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } Py_DECREF(wsgi_compiled_node); up.loader_dict = PyModule_GetDict(wsgi_eval_module); if (!up.loader_dict) { PyErr_Print(); exit(UWSGI_FAILED_APP_CODE); } if (up.callable) { wsgi_eval_callable = PyDict_GetItemString(up.loader_dict, up.callable); } else { wsgi_eval_callable = PyDict_GetItemString(up.loader_dict, "application"); } if (wsgi_eval_callable) { if (!PyFunction_Check(wsgi_eval_callable) && !PyCallable_Check(wsgi_eval_callable)) { uwsgi_log( "you must define a callable object in your code\n"); exit(UWSGI_FAILED_APP_CODE); } } return wsgi_eval_callable; #endif }
static int modena_model_t_init(modena_model_t *self, PyObject *args, PyObject *kwds) { PyObject *pParameters=NULL, *pModel=NULL; char *modelId=NULL; static char *kwlist[] = {"model", "modelId", "parameters"}; if ( !PyArg_ParseTupleAndKeywords ( args, kwds, "|OsO", kwlist, &pModel, &modelId, &pParameters ) ) { return -1; } if(!pModel) { PyObject *pName = PyString_FromString("modena.SurrogateModel"); if(!pName){ Modena_PyErr_Print(); } PyObject *pModule = PyImport_Import(pName); Py_DECREF(pName); if(!pModule){ Modena_PyErr_Print(); } PyObject *pDict = PyModule_GetDict(pModule); // Borrowed ref if(!pDict){ Modena_PyErr_Print(); } pName = PyString_FromString("SurrogateModel"); if(!pName){ Modena_PyErr_Print(); } PyObject *sModel = PyObject_GetItem(pDict, pName); Py_DECREF(pName); if(!sModel){ Modena_PyErr_Print(); } self->pModel = PyObject_CallMethod(sModel, "load", "(z)", modelId); Py_DECREF(sModel); if(!self->pModel){ Modena_PyErr_Print(); } modena_model_get_minMax(self); Py_DECREF(pModule); } else { Py_INCREF(pModel); self->pModel = pModel; // Set everything to zero self->inputs_minMax_size = 0; self->inputs_min = NULL; self->inputs_max = NULL; } //PyObject_Print(self->pModel, stdout, 0); //printf("\n"); PyObject *pOutputs = PyObject_GetAttrString(self->pModel, "outputs"); if(!pOutputs){ Modena_PyErr_Print(); } self->outputs_size = PyDict_Size(pOutputs); Py_DECREF(pOutputs); PyObject *pMaxArgPos = PyObject_CallMethod ( self->pModel, "inputs_max_argPos", NULL ); if(!pMaxArgPos){ Modena_PyErr_Print(); } self->inputs_size = 1 + PyInt_AsSsize_t(pMaxArgPos); Py_DECREF(pMaxArgPos); self->inherited_inputs_size = 0; // Avoiding double indirection in modena_model_call // Use modena_function_new to construct, then copy function pointer self->mf = modena_function_new(self); self->function = self->mf->function; self->argPos_used = malloc ( (self->inputs_size + self->inherited_inputs_size)*sizeof(bool) ); modena_model_read_substituteModels(self); if(!pParameters) { pParameters = PyObject_GetAttrString(self->pModel, "parameters"); if(!pParameters){ Modena_PyErr_Print(); } } else { Py_INCREF(pParameters); } PyObject *pSeq = PySequence_Fast(pParameters, "expected a sequence"); self->parameters_size = PySequence_Size(pParameters); self->parameters = malloc(self->parameters_size*sizeof(double)); size_t i; for(i = 0; i < self->parameters_size; i++) { self->parameters[i] = PyFloat_AsDouble(PyList_GET_ITEM(pSeq, i)); } Py_DECREF(pSeq); Py_DECREF(pParameters); if(PyErr_Occurred()){ Modena_PyErr_Print(); } return 0; }
PyMODINIT_FUNC initGameTypesPythonBinding(void) { PyObject *m; PyObject *dict; m = PyModule_Create(&GameTypes_module_def); PyDict_SetItemString(PySys_GetObject("modules"), GameTypes_module_def.m_name, m); dict = PyModule_GetDict(m); for (int init_getset= 1; init_getset > -1; init_getset--) { /* run twice, once to init the getsets another to run PyType_Ready */ PyType_Ready_Attr(dict, BL_ActionActuator, init_getset); PyType_Ready_Attr(dict, BL_Shader, init_getset); PyType_Ready_Attr(dict, BL_ShapeActionActuator, init_getset); PyType_Ready_Attr(dict, BL_ArmatureObject, init_getset); PyType_Ready_Attr(dict, BL_ArmatureActuator, init_getset); PyType_Ready_Attr(dict, BL_ArmatureConstraint, init_getset); PyType_Ready_AttrPtr(dict, BL_ArmatureBone, init_getset); PyType_Ready_AttrPtr(dict, BL_ArmatureChannel, init_getset); // PyType_Ready_Attr(dict, CPropValue, init_getset); // doesn't use Py_Header PyType_Ready_Attr(dict, CListValue, init_getset); PyType_Ready_Attr(dict, CListWrapper, init_getset); PyType_Ready_Attr(dict, CValue, init_getset); PyType_Ready_Attr(dict, KX_ArmatureSensor, init_getset); PyType_Ready_Attr(dict, KX_BlenderMaterial, init_getset); PyType_Ready_Attr(dict, KX_Camera, init_getset); PyType_Ready_Attr(dict, KX_CameraActuator, init_getset); PyType_Ready_Attr(dict, KX_CharacterWrapper, init_getset); PyType_Ready_Attr(dict, KX_ConstraintActuator, init_getset); PyType_Ready_Attr(dict, KX_ConstraintWrapper, init_getset); PyType_Ready_Attr(dict, KX_GameActuator, init_getset); PyType_Ready_Attr(dict, KX_GameObject, init_getset); PyType_Ready_Attr(dict, KX_LibLoadStatus, init_getset); PyType_Ready_Attr(dict, KX_LightObject, init_getset); PyType_Ready_Attr(dict, KX_FontObject, init_getset); PyType_Ready_Attr(dict, KX_MeshProxy, init_getset); PyType_Ready_Attr(dict, KX_MouseFocusSensor, init_getset); PyType_Ready_Attr(dict, KX_NearSensor, init_getset); PyType_Ready_Attr(dict, KX_NetworkMessageActuator, init_getset); PyType_Ready_Attr(dict, KX_NetworkMessageSensor, init_getset); PyType_Ready_Attr(dict, KX_ObjectActuator, init_getset); PyType_Ready_Attr(dict, KX_ParentActuator, init_getset); PyType_Ready_Attr(dict, KX_PolyProxy, init_getset); PyType_Ready_Attr(dict, KX_RadarSensor, init_getset); PyType_Ready_Attr(dict, KX_RaySensor, init_getset); PyType_Ready_Attr(dict, KX_SCA_AddObjectActuator, init_getset); PyType_Ready_Attr(dict, KX_SCA_DynamicActuator, init_getset); PyType_Ready_Attr(dict, KX_SCA_EndObjectActuator, init_getset); PyType_Ready_Attr(dict, KX_SCA_ReplaceMeshActuator, init_getset); PyType_Ready_Attr(dict, KX_Scene, init_getset); PyType_Ready_Attr(dict, KX_WorldInfo, init_getset); PyType_Ready_Attr(dict, KX_NavMeshObject, init_getset); PyType_Ready_Attr(dict, KX_SceneActuator, init_getset); PyType_Ready_Attr(dict, KX_SoundActuator, init_getset); PyType_Ready_Attr(dict, KX_StateActuator, init_getset); PyType_Ready_Attr(dict, KX_SteeringActuator, init_getset); PyType_Ready_Attr(dict, KX_TouchSensor, init_getset); PyType_Ready_Attr(dict, KX_TrackToActuator, init_getset); PyType_Ready_Attr(dict, KX_VehicleWrapper, init_getset); PyType_Ready_Attr(dict, KX_VertexProxy, init_getset); PyType_Ready_Attr(dict, KX_VisibilityActuator, init_getset); PyType_Ready_Attr(dict, KX_MouseActuator, init_getset); PyType_Ready_Attr(dict, PyObjectPlus, init_getset); PyType_Ready_Attr(dict, SCA_2DFilterActuator, init_getset); PyType_Ready_Attr(dict, SCA_ANDController, init_getset); // PyType_Ready_Attr(dict, SCA_Actuator, init_getset); // doesn't use Py_Header PyType_Ready_Attr(dict, SCA_ActuatorSensor, init_getset); PyType_Ready_Attr(dict, SCA_AlwaysSensor, init_getset); PyType_Ready_Attr(dict, SCA_DelaySensor, init_getset); PyType_Ready_Attr(dict, SCA_ILogicBrick, init_getset); PyType_Ready_Attr(dict, SCA_IObject, init_getset); PyType_Ready_Attr(dict, SCA_ISensor, init_getset); PyType_Ready_Attr(dict, SCA_JoystickSensor, init_getset); PyType_Ready_Attr(dict, SCA_KeyboardSensor, init_getset); PyType_Ready_Attr(dict, SCA_MouseSensor, init_getset); PyType_Ready_Attr(dict, SCA_NANDController, init_getset); PyType_Ready_Attr(dict, SCA_NORController, init_getset); PyType_Ready_Attr(dict, SCA_ORController, init_getset); PyType_Ready_Attr(dict, SCA_PropertyActuator, init_getset); PyType_Ready_Attr(dict, SCA_PropertySensor, init_getset); PyType_Ready_Attr(dict, SCA_PythonController, init_getset); PyType_Ready_Attr(dict, SCA_RandomActuator, init_getset); PyType_Ready_Attr(dict, SCA_RandomSensor, init_getset); PyType_Ready_Attr(dict, SCA_XNORController, init_getset); PyType_Ready_Attr(dict, SCA_XORController, init_getset); PyType_Ready_Attr(dict, SCA_IController, init_getset); PyType_Ready_Attr(dict, SCA_PythonJoystick, init_getset); PyType_Ready_Attr(dict, SCA_PythonKeyboard, init_getset); PyType_Ready_Attr(dict, SCA_PythonMouse, init_getset); } #ifdef USE_MATHUTILS /* Init mathutils callbacks */ KX_GameObject_Mathutils_Callback_Init(); KX_ObjectActuator_Mathutils_Callback_Init(); KX_WorldInfo_Mathutils_Callback_Init(); KX_BlenderMaterial_Mathutils_Callback_Init(); #endif return m; }