static int py_globals(lua_State *L) { PyObject *globals; if (lua_gettop(L) != 0) { luaL_error(L, "invalid arguments"); return 0; } globals = PyEval_GetGlobals(); if (!globals) { PyObject *module = PyImport_AddModule("__main__"); if (!module) { luaL_error(L, "Can't get __main__ module"); return 0; } globals = PyModule_GetDict(module); } if (!globals) { PyErr_Print(); luaL_error(L, "can't get globals"); return 0; } return py_convert_custom(L, globals, 1); }
// Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); #if PY_VERSION_HEX >= 0x03000000 // TODO(bhy) temporary workaround for Python 3. // should figure out a way to avoid binary incompatibilities as the Python 2 // version did. FILE *fs = fopen(f, "r"); #else // Let python open the file to avoid potential binary incompatibilities. PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r")); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); FILE *fs = PyFile_AsFile(file.get()); #endif PyObject* result = PyRun_File(fs, f, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); }
// Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // Set suitable default values for global and local dicts. object none; if (global.ptr() == none.ptr()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.ptr() == none.ptr()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); // Let python open the file to avoid potential binary incompatibilities. PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r")); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); PyObject* result = PyRun_File(PyFile_AsFile(file.get()), f, Py_file_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); }
static PyObject *py_ue_swidget_assign(ue_PySWidget *self, PyObject * args) { char *global_name; if (!PyArg_ParseTuple(args, "s:assign", &global_name)) { return nullptr; } PyObject *py_globals = PyEval_GetGlobals(); if (!py_globals) { return PyErr_Format(PyExc_Exception, "unable to retrieve globals"); } if (!PyDict_GetItemString(py_globals, global_name)) { PyErr_Clear(); return PyErr_Format(PyExc_Exception, "global \"%s\" not found", global_name); } if (PyDict_SetItemString(py_globals, global_name, (PyObject *)self) < 0) { return PyErr_Format(PyExc_Exception, "unable to assign global \"%s\" to SWidget", global_name); } Py_RETURN_SLATE_SELF; }
static int shell_set_global_var(MYX_GRT *grt, const char *var_name, MYX_GRT_VALUE *value) { PyObject *object= (PyObject*)myx_py_grtvalue_create(value); PyObject *globals= PyEval_GetGlobals(); PyDict_SetItemString(globals, var_name, object); Py_DECREF(object); return 0; }
static MYX_GRT_VALUE * shell_get_global_var(MYX_GRT *grt, const char *var_name) { PyObject *globals= PyEval_GetGlobals(); PyObject *item; item= PyDict_GetItemString(globals, var_name); if (!item) return NULL; return myx_py_object_to_value(item); }
static void _compose_initialize(PyComposeObject* cmps) { cmps->expect_data = 0; cmps->started = 0; cmps->stepping = 0; cmps->paused_on_step = 0; cmps->generators_allocated = INITIAL_STACK_SIZE; cmps->generators_base = (PyObject**) malloc(cmps->generators_allocated * sizeof(PyObject*)); cmps->generators_top = cmps->generators_base; cmps->messages_base = (PyObject**) calloc(QUEUE_SIZE, sizeof(PyObject*)); cmps->messages_start = cmps->messages_base; cmps->messages_end = cmps->messages_base; cmps->weakreflist = NULL; cmps->frame = PyFrame_New(PyThreadState_GET(), py_code, PyEval_GetGlobals(), NULL); Py_CLEAR(cmps->frame->f_back); }
object BOOST_PYTHON_DECL exec_statement(str string, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *s = python::extract<char *>(string); PyObject* result = PyRun_String(s, Py_single_input, global.ptr(), local.ptr()); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); }
bool sequenceToArgcArgv(PyObject* argList, int* argc, char*** argv, const char* defaultAppName) { if (!PySequence_Check(argList)) return false; if (!defaultAppName) defaultAppName = "PySideApplication"; // Check all items Shiboken::AutoDecRef args(PySequence_Fast(argList, 0)); int numArgs = PySequence_Fast_GET_SIZE(argList); for (int i = 0; i < numArgs; ++i) { PyObject* item = PySequence_Fast_GET_ITEM(args.object(), i); if (!PyString_Check(item) && !PyUnicode_Check(item)) return false; } bool hasEmptyArgList = numArgs == 0; if (hasEmptyArgList) numArgs = 1; *argc = numArgs; *argv = new char*[*argc]; if (hasEmptyArgList) { // Try to get the script name PyObject* globals = PyEval_GetGlobals(); PyObject* appName = PyDict_GetItemString(globals, "__file__"); (*argv)[0] = strdup(appName ? PyString_AS_STRING(appName) : defaultAppName); } else { for (int i = 0; i < numArgs; ++i) { PyObject* item = PySequence_Fast_GET_ITEM(args.object(), i); char* string; if (PyUnicode_Check(item)) { Shiboken::AutoDecRef utf8(PyUnicode_AsUTF8String(item)); string = strdup(PyString_AS_STRING(utf8.object())); } else { string = strdup(PyString_AS_STRING(item)); } (*argv)[i] = string; } } return true; }
/** * Returns the globals dictionary **/ static void py_globals(lua_State *L) { PyObject *globals; if (lua_gettop(L) != 0) { lua_error(L, "invalid arguments"); } globals = PyEval_GetGlobals(); if (!globals) { PyObject *module = PyImport_AddModule("__main__"); if (!module) { lua_error(L, "Can't get __main__ module"); } globals = PyModule_GetDict(module); } if (!globals) { lua_new_error(L, "can't get globals"); } Py_INCREF(globals); push_pyobject_container(L, globals, 1); }
/** * 完成import... **/ PyObject* Ps_Import(PyObject *self, PyObject *args, PyObject *kws) { //struct _ts *state; char *module; char *arglist[] = {"module", 0}; FILE *f; PyObject *m; //PyObject *local = NULL, *global = NULL; if(!PyArg_ParseTupleAndKeywords(args, kws, "s:import", arglist, &module)) { Ps_Log("Import args or kws is faile, function is that ps_import(module)\n", Ps_LOG_WARING); return NULL; } if((f = (open_file(NULL, module))) == NULL) { Ps_LogFormat("Open file %s failed\n", Ps_LOG_WARING, module); goto error; } /*state = PyThreadState_Get(); if(state->frame) { local = state->frame->f_locals; global = state->frame->f_globals; }*/ if((m = __import__(f, module, NULL, NULL, PyEval_GetLocals(), PyEval_GetGlobals())) == NULL) { if(PyErr_Occurred()) { return NULL; } goto error; } Py_INCREF(Py_True); return Py_True; error: PyErr_SetString(PyExc_ImportError, "Import error"); return NULL; }
void PyC_FileAndNum(const char **filename, int *lineno) { PyFrameObject *frame; if (filename) *filename= NULL; if (lineno) *lineno = -1; if (!(frame= PyThreadState_GET()->frame)) { return; } /* when executing a script */ if (filename) { *filename = _PyUnicode_AsString(frame->f_code->co_filename); } /* when executing a module */ if(filename && *filename == NULL) { /* try an alternative method to get the filename - module based * references below are all borrowed (double checked) */ PyObject *mod_name= PyDict_GetItemString(PyEval_GetGlobals(), "__name__"); if(mod_name) { PyObject *mod= PyDict_GetItem(PyImport_GetModuleDict(), mod_name); if(mod) { *filename= PyModule_GetFilename(mod); } /* unlikely, fallback */ if(*filename == NULL) { *filename= _PyUnicode_AsString(mod_name); } } } if (lineno) { *lineno = PyFrame_GetLineNumber(frame); } }
PyTaskletObject * PyTasklet_New(PyTypeObject *type, PyObject *func) { PyThreadState *ts = PyThreadState_GET(); PyTaskletObject *t; /* we always need a cstate, so be sure to initialize */ if (ts->st.initial_stub == NULL) return PyTasklet_New_M(type, func); if (func != NULL && !PyCallable_Check(func)) TYPE_ERROR("tasklet function must be a callable", NULL); if (type == NULL) type = &PyTasklet_Type; assert(PyType_IsSubtype(type, &PyTasklet_Type)); t = (PyTaskletObject *) type->tp_alloc(type, 0); if (t != NULL) { *(int*)&t->flags = 0; t->next = NULL; t->prev = NULL; t->f.frame = NULL; if (func == NULL) func = Py_None; Py_INCREF(func); t->tempval = func; t->tsk_weakreflist = NULL; Py_INCREF(ts->st.initial_stub); t->cstate = ts->st.initial_stub; t->def_globals = PyEval_GetGlobals(); Py_XINCREF(t->def_globals); if (ts != slp_initial_tstate) { /* make sure to kill tasklets with their thread */ if (slp_ensure_linkage(t)) { Py_DECREF(t); return NULL; } } } return t; }
// Execute python source code from file filename. // global and local are the global and local scopes respectively, // used during execution. object BOOST_PYTHON_DECL exec_file(str filename, object global, object local) { // Set suitable default values for global and local dicts. if (global.is_none()) { if (PyObject *g = PyEval_GetGlobals()) global = object(detail::borrowed_reference(g)); else global = dict(); } if (local.is_none()) local = global; // should be 'char const *' but older python versions don't use 'const' yet. char *f = python::extract<char *>(filename); // Let python open the file to avoid potential binary incompatibilities. #if PY_VERSION_HEX >= 0x03040000 FILE *fs = _Py_fopen(f, "r"); #elif PY_VERSION_HEX >= 0x03000000 PyObject *fo = Py_BuildValue("s", f); FILE *fs = _Py_fopen(fo, "r"); Py_DECREF(fo); #else PyObject *pyfile = PyFile_FromString(f, const_cast<char*>("r")); if (!pyfile) throw std::invalid_argument(std::string(f) + " : no such file"); python::handle<> file(pyfile); FILE *fs = PyFile_AsFile(file.get()); #endif int closeit = 1; // Close file before PyRun returns PyObject* result = PyRun_FileEx(fs, f, Py_file_input, global.ptr(), local.ptr(), closeit); if (!result) throw_error_already_set(); return object(detail::new_reference(result)); }
/*调用这个函数前必须加锁*/ static PyObject* from_web_import_as(char *website, char *module, char *as) { #define Ps_NAME_MAX (sizeof(unsigned int) << 1 + 10) #define WEB_PATH_MAX 1024 char buffer[WEB_PATH_MAX]; char file_name[Ps_NAME_MAX]; /*加载函数的函数指针*/ PyObject* (*loader)(FILE *f, char *name, char *path, char *as, PyObject *local, PyObject *global); FILE *f; PyObject *m; assert(website); assert(module); #if (PLATFORM & WIN32) || (PLATFORM & WIN64) sprintf(file_name, "cache\\%X", file_name_no); #elif (PLATFORM & LINUX32) || (PLATFORM & LINUX64) sprintf(file_name, "cache/%X", file_name_no); #endif #ifdef IMPORT_DEBUG Ps_LogFormat("Creat temp file %s\n", Ps_LOG_NORMAL, file_name); Ps_LogFormat("From %s import %s\n", Ps_LOG_NORMAL, website, module); #endif file_name_no ++; if((f = fopen((char*)file_name, "w")) == NULL) { Ps_Log("Create temp file failed\n", Ps_LOG_WARING); PyErr_SetString(PyExc_ImportError, "Create temp file failed"); return NULL; } /*下载py文件*/ if(!get_url(website, module, FALSE, buffer, WEB_PATH_MAX)) { Ps_Log("Get url failed\n", Ps_LOG_WARING); PyErr_SetString(PyExc_ImportError, "The path to get python module is too long"); return NULL; } loader = __import__; if(!Ps_DownloadTimeout(buffer, f, TIME_OUT)) { Ps_Log("Cannot download %s's py file\n", Ps_LOG_WARING); /*再次尝试下载pyc文件*/ // (void)get_url(website, module, TRUE, buffer, WEB_PATH_MAX); if(!Ps_DownloadTimeout(buffer, f, TIME_OUT)) { Ps_Log("Download pyc file also failed\n", Ps_LOG_WARING); PyErr_Format(PyExc_ImportError, "Cannot download module %s file from %s\n", module, website); return NULL; } /*使用加载pyc文件的加载函数*/ loader = __import__compiled; } /*加载py文件*/ fclose(f); if((f = fopen(file_name, "r")) == NULL) { Ps_Log("Open temp file failed\n", Ps_LOG_WARING); PyErr_SetString(PyExc_ImportError, "open temp file failed"); return NULL; } if(!(m = loader(f, module, NULL, as, PyEval_GetLocals(), PyEval_GetGlobals()))) { fclose(f); return NULL; } #ifdef IMPORT_DEBUG Ps_Log("******************************************", Ps_LOG_NORMAL); Ps_LogObject(m, Ps_LOG_NORMAL); Ps_Log("******************************************", Ps_LOG_NORMAL); #endif Py_INCREF(Py_True); return Py_True; }
std::vector<cmonster::core::Token> FunctionMacro::operator()( clang::SourceLocation const& expansion_location, std::vector<cmonster::core::Token> const& arguments) const { // Create the arguments tuple. ScopedPyObject args_tuple = PyTuple_New(arguments.size()); if (!args_tuple) throw std::runtime_error("Failed to create argument tuple"); for (Py_ssize_t i = 0; i < static_cast<Py_ssize_t>(arguments.size()); ++i) { Token *token = create_token(m_preprocessor, arguments[i]); PyTuple_SetItem(args_tuple, i, reinterpret_cast<PyObject*>(token)); } // Set the "preprocessor" and "location" global variables. // // XXX How do we create a closure via the C API? It would be better if we // could bind a function to the preprocessor it was created with, when we // define the function. PyObject *globals = PyEval_GetGlobals(); if (globals) { PyObject *key = PyUnicode_FromString("preprocessor"); if (!key) throw python_exception(); Py_INCREF((PyObject*)m_preprocessor); PyDict_SetItem(globals, key, (PyObject*)m_preprocessor); cmonster::core::Preprocessor &pp = get_preprocessor(m_preprocessor); SourceLocation *location = create_source_location( expansion_location, pp.getClangPreprocessor().getSourceManager()); if (!location) throw python_exception(); key = PyUnicode_FromString("location"); if (!key) throw python_exception(); PyDict_SetItem(globals, key, (PyObject*)location); } // Call the function. ScopedPyObject py_result = PyObject_Call(m_callable, args_tuple, NULL); if (!py_result) throw python_exception(); // Transform the result. std::vector<cmonster::core::Token> result; if (py_result == Py_None) return result; // Is it a string? If so, tokenize it. if (PyUnicode_Check(py_result)) { ScopedPyObject utf8(PyUnicode_AsUTF8String(py_result)); if (utf8) { char *u8_chars; Py_ssize_t u8_size; if (PyBytes_AsStringAndSize(utf8, &u8_chars, &u8_size) == -1) { throw python_exception(); } else { cmonster::core::Preprocessor &pp = get_preprocessor(m_preprocessor); result = pp.tokenize(u8_chars, u8_size); return result; } } else { throw python_exception(); } } // If it's not a string, it should be a sequence of Token objects. if (!PySequence_Check(py_result)) { throw python_exception(PyExc_TypeError, "macro functions must return a sequence of tokens"); } const Py_ssize_t seqlen = PySequence_Size(py_result); if (seqlen == -1) { throw python_exception(); } else { for (Py_ssize_t i = 0; i < seqlen; ++i) { ScopedPyObject token_ = PySequence_GetItem(py_result, i); if (PyObject_TypeCheck(token_, get_token_type())) { Token *token = (Token*)(PyObject*)token_; result.push_back(get_token(token)); } else { // Invalid return value. throw python_exception(PyExc_TypeError, "macro functions must return a sequence of tokens"); } } } return result; }