当前位置: 首页>>代码示例>>C++>>正文


C++ PyModule_GetDict函数代码示例

本文整理汇总了C++中PyModule_GetDict函数的典型用法代码示例。如果您正苦于以下问题:C++ PyModule_GetDict函数的具体用法?C++ PyModule_GetDict怎么用?C++ PyModule_GetDict使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了PyModule_GetDict函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: PyFrame_New

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))
//.........这里部分代码省略.........
开发者ID:Illirgway,项目名称:cpython,代码行数:101,代码来源:frameobject.c

示例2: fixup_ulcase

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);
}
开发者ID:JupiterSmalltalk,项目名称:openqwaq,代码行数:63,代码来源:_localemodule.c

示例3: throw

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.");
	}

	
}
开发者ID:DavidHammen,项目名称:chrono,代码行数:71,代码来源:ChPython.cpp

示例4: initzbar

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);
}
开发者ID:AquaGeek,项目名称:zbar,代码行数:85,代码来源:zbarmodule.c

示例5: Python3_Init

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;
}
开发者ID:tonymagro,项目名称:viw,代码行数:71,代码来源:if_python3.c

示例6: _Py_InitializeEx_Private

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);
//.........这里部分代码省略.........
开发者ID:yoongkang,项目名称:cpython,代码行数:101,代码来源:pylifecycle.c

示例7: initumath

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");
//.........这里部分代码省略.........
开发者ID:naghmouchi,项目名称:numpy,代码行数:101,代码来源:umathmodule.c

示例8: PyInit_soy_widgets

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;
}
开发者ID:RONNCC,项目名称:pysoy,代码行数:81,代码来源:__init__.c

示例9: start_intercloudGW

/*-------------------------------------------------------------------------------*/
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 ) );
	}
}
开发者ID:MarouenMechtri,项目名称:accords-platform-1,代码行数:100,代码来源:intercloudGWAction.c

示例10: download_thread

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);
}
开发者ID:colin-zhou,项目名称:reserve,代码行数:61,代码来源:download.cpp

示例11: MOD_INIT_DECL

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 )
//.........这里部分代码省略.........
开发者ID:mesmerx,项目名称:linuxopenmusic,代码行数:101,代码来源:module.pip._vendor.requests.status_codes.cpp

示例12: initModule

/* 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);
//.........这里部分代码省略.........
开发者ID:Tojaj,项目名称:rpm,代码行数:101,代码来源:rpmmodule.c

示例13: gplp_load_base

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;
}
开发者ID:nzinfo,项目名称:gnumeric,代码行数:81,代码来源:python-loader.c

示例14: initwarpC

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
}
开发者ID:radiasoft,项目名称:warp,代码行数:66,代码来源:warpC_Forthon.c

示例15: init_uwsgi_app

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();

	}
//.........这里部分代码省略.........
开发者ID:20tab,项目名称:uwsgi,代码行数:101,代码来源:pyloader.c


注:本文中的PyModule_GetDict函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。