• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ PyObject_GetAttrString函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: ExclusionFilter_names_to_ccn

static PyObject *
ExclusionFilter_names_to_ccn(PyObject *py_obj_Names)
{
	PyObject *py_iterator = NULL, *py_item = NULL;
	PyObject *py_exclude, *py_o;
	struct ccn_charbuf *exclude, *name;
	int r;

	//  Build exclusion list - This uses explicit exclusion rather than
	//                         Bloom filters as Bloom will be deprecated
	//  IMPORTANT:  Exclusion component list must be sorted following
	//              "Canonical CCNx ordering"
	//              http://www.ccnx.org/releases/latest/doc/technical/CanonicalOrder.html
	//              in which shortest components go first.
	// This sorting is expected to be handled on the Python side, not here.

	assert(py_obj_Names);

	py_exclude = CCNObject_New_charbuf(EXCLUSION_FILTER, &exclude);
	JUMP_IF_NULL(py_exclude, error);

	if (py_obj_Names == Py_None)
		return py_exclude;

	r = ccn_charbuf_append_tt(exclude, CCN_DTAG_Exclude, CCN_DTAG);
	JUMP_IF_NEG_MEM(r, error);

	// This code is similar to what's used in Name;
	// could probably be generalized.

	py_iterator = PyObject_GetIter(py_obj_Names);
	JUMP_IF_NULL(py_iterator, error);

	while ((py_item = PyIter_Next(py_iterator))) {
		int type;

		if (!PyObject_IsInstance(py_item, g_type_Name)) {
			PyErr_SetString(PyExc_ValueError, "Expected Name element");
			goto error;
		}

		py_o = PyObject_GetAttrString(py_item, "type");
		JUMP_IF_NULL(py_o, error);

		type = PyLong_AsLong(py_o);
		Py_DECREF(py_o);
		JUMP_IF_ERR(error);

		if (type == 0) {
			py_o = PyObject_GetAttrString(py_item, "ccn_data");
			JUMP_IF_NULL(py_o, error);

			if (!CCNObject_IsValid(NAME, py_o)) {
				Py_DECREF(py_o);
				PyErr_SetString(PyExc_TypeError, "Expected CCN Name");
				goto error;
			}

			name = CCNObject_Get(NAME, py_o);

			/* append without CCN name tag */
			assert(name->length >= 4);
			r = ccn_charbuf_append(exclude, name->buf + 1, name->length - 2);
			Py_DECREF(py_o);
			JUMP_IF_NEG_MEM(r, error);
		} else if (type == 1) {
			r = ccn_charbuf_append_tt(exclude, CCN_DTAG_Any, CCN_DTAG);
			JUMP_IF_NEG_MEM(r, error);

			r = ccn_charbuf_append_closer(exclude);
			JUMP_IF_NEG_MEM(r, error);
		} else {
			PyErr_SetString(PyExc_ValueError, "Unhandled Name type");
			goto error;
		}

		Py_CLEAR(py_item);
	}
	Py_CLEAR(py_iterator);

	r = ccn_charbuf_append_closer(exclude); /* </Exclude> */
	JUMP_IF_NEG_MEM(r, error);

	return py_exclude;

error:
	Py_XDECREF(py_item);
	Py_XDECREF(py_iterator);
	Py_XDECREF(py_exclude);
	return NULL;
}
开发者ID:chris-wood,项目名称:PyCCN,代码行数:91,代码来源:methods_interest.c


示例2: GREENLET_NOINLINE

static int GREENLET_NOINLINE(g_initialstub)(void* mark)
{
	int err;
	PyObject *o, *run;
	PyObject *exc, *val, *tb;
	PyObject *run_info;
	PyGreenlet* self = ts_target;
	PyObject* args = ts_passaround_args;
	PyObject* kwargs = ts_passaround_kwargs;

	/* save exception in case getattr clears it */
	PyErr_Fetch(&exc, &val, &tb);
	/* self.run is the object to call in the new greenlet */
	run = PyObject_GetAttrString((PyObject*) self, "run");
	if (run == NULL) {
		Py_XDECREF(exc);
		Py_XDECREF(val);
		Py_XDECREF(tb);
		return -1;
	}
	/* restore saved exception */
	PyErr_Restore(exc, val, tb);

	/* recheck the state in case getattr caused thread switches */
	if (!STATE_OK) {
		Py_DECREF(run);
		return -1;
	}

	/* recheck run_info in case greenlet reparented anywhere above */
	run_info = green_statedict(self);
	if (run_info == NULL || run_info != ts_current->run_info) {
		Py_DECREF(run);
		PyErr_SetString(PyExc_GreenletError, run_info
		                ? "cannot switch to a different thread"
		                : "cannot switch to a garbage collected greenlet");
		return -1;
	}

	/* by the time we got here another start could happen elsewhere,
	 * that means it should now be a regular switch
	 */
	if (PyGreenlet_STARTED(self)) {
		Py_DECREF(run);
		ts_passaround_args = args;
		ts_passaround_kwargs = kwargs;
		return 1;
	}

	/* start the greenlet */
	self->stack_start = NULL;
	self->stack_stop = (char*) mark;
	if (ts_current->stack_start == NULL) {
		/* ts_current is dying */
		self->stack_prev = ts_current->stack_prev;
	}
	else {
		self->stack_prev = ts_current;
	}
	self->top_frame = NULL;
	self->exc_type = NULL;
	self->exc_value = NULL;
	self->exc_traceback = NULL;
	self->recursion_depth = PyThreadState_GET()->recursion_depth;

	/* restore arguments in case they are clobbered */
	ts_target = self;
	ts_passaround_args = args;
	ts_passaround_kwargs = kwargs;

	/* perform the initial switch */
	err = g_switchstack();

	/* returns twice!
	   The 1st time with err=1: we are in the new greenlet
	   The 2nd time with err=0: back in the caller's greenlet
	*/
	if (err == 1) {
		/* in the new greenlet */
		PyGreenlet* origin;
#if GREENLET_USE_TRACING
		PyObject* tracefunc;
#endif
		PyObject* result;
		PyGreenlet* parent;
		self->stack_start = (char*) 1;  /* running */

		/* grab origin while we still can */
		origin = ts_origin;
		ts_origin = NULL;

		/* now use run_info to store the statedict */
		o = self->run_info;
		self->run_info = green_statedict(self->parent);
		Py_INCREF(self->run_info);
		Py_XDECREF(o);

#if GREENLET_USE_TRACING
		if ((tracefunc = PyDict_GetItem(self->run_info, ts_tracekey)) != NULL) {
			Py_INCREF(tracefunc);
//.........这里部分代码省略.........
开发者ID:Infinidat,项目名称:greenlet,代码行数:101,代码来源:greenlet.c


示例3: API_wouldBlock_gevent

int API_wouldBlock_gevent(void *sock, int fd, int ops, int timeout)
{
    /* Setup gevent and yield to gevent hub */

    static int once = 1;
    static PyObject *sockmodule = NULL;
    static PyObject *waitread = NULL;
    static PyObject *waitwrite = NULL;

    PyObject *resObject = NULL;
    PyObject *argList;
    PyObject *kwargList;

    if (once)
    {
        /*FIXME: References for module, class or methods are never released */
        sockmodule = PyImport_ImportModule ("gevent.socket");

        if (sockmodule == NULL)
        {
            PRINTMARK();
            return -1;
        }

        waitread = PyObject_GetAttrString(sockmodule, "wait_read");
        waitwrite = PyObject_GetAttrString(sockmodule, "wait_write");

        if (waitread == NULL || waitwrite == NULL)
        {
            PRINTMARK();
            return -1;
        }

        if (!PyFunction_Check(waitread) || !PyFunction_Check(waitwrite))
        {
            PRINTMARK();
            return -1;
        }

        PRINTMARK();
        once = 0;
    }


    PRINTMARK();
    //FIXME: do this once
    argList = PyTuple_New(1);
    PyTuple_SET_ITEM(argList, 0, PyInt_FromLong(fd));
    kwargList = PyDict_New();
    PyDict_SetItemString(kwargList, "timeout", PyInt_FromLong(timeout));

    PRINTMARK();

    switch (ops)
    {
    case 1:
        PRINTMARK();

        resObject = PyObject_Call (waitread, argList, kwargList);
        PRINTMARK();
        break;

    case 2:
        PRINTMARK();
        resObject = PyObject_Call (waitwrite, argList, kwargList);
        PRINTMARK();
        break;
    }

    Py_DECREF(argList);
    Py_DECREF(kwargList);

    if (resObject == NULL)
    {
        if (!PyErr_Occurred())
        {
            PyErr_Format(PyExc_RuntimeError, "umemcached: Python exception not set for operation %d", ops);
        }
        PRINTMARK();
        return 0;
    }

    PRINTMARK();
    Py_DECREF(resObject);
    PRINTMARK();

    return 1;
}
开发者ID:sreekanth-anubolu,项目名称:ultramemcached,代码行数:88,代码来源:umemcached.cpp


示例4: PyTuple_GetItem

PyObject *py_uwsgi_gevent_request(PyObject * self, PyObject * args) {

	PyObject *py_wsgi_req = PyTuple_GetItem(args, 0);
	struct wsgi_request *wsgi_req = (struct wsgi_request *) PyLong_AsLong(py_wsgi_req);

	PyObject *greenlet_switch = NULL;

	PyObject *current_greenlet = GET_CURRENT_GREENLET;
	// another hack to retrieve the current wsgi_req;
	PyObject_SetAttrString(current_greenlet, "uwsgi_wsgi_req", py_wsgi_req);

	// if in edge-triggered mode read from socket now !!!
	if (wsgi_req->socket->edge_trigger) {
		int status = wsgi_req->socket->proto(wsgi_req);
		if (status < 0) {
			goto end;
		}
		goto request;
	}

	greenlet_switch = PyObject_GetAttrString(current_greenlet, "switch");

	for(;;) {
		int ret = uwsgi.wait_read_hook(wsgi_req->fd, uwsgi.socket_timeout);
                wsgi_req->switches++;

                if (ret <= 0) {
                        goto end;
                }

                int status = wsgi_req->socket->proto(wsgi_req);
                if (status < 0) {
                        goto end;
                }
                else if (status == 0) {
                        break;
                }
	}

request:

#ifdef UWSGI_ROUTING
	if (uwsgi_apply_routes(wsgi_req) == UWSGI_ROUTE_BREAK) {
		goto end;
	}
#endif

	for(;;) {
		if (uwsgi.p[wsgi_req->uh->modifier1]->request(wsgi_req) <= UWSGI_OK) {
			goto end;
		}
		wsgi_req->switches++;
		// switch after each yield
		GEVENT_SWITCH;
	}

end:
	if (greenlet_switch) {
		Py_DECREF(greenlet_switch);
	}

	Py_DECREF(current_greenlet);

	uwsgi_close_request(wsgi_req);
	free_req_queue;


	if (uwsgi.workers[uwsgi.mywid].manage_next_request == 0) {
		int running_cores = 0;
		int i;
                for(i=0;i<uwsgi.async;i++) {
                        if (uwsgi.workers[uwsgi.mywid].cores[i].in_request) {
                                running_cores++;
                        }
                }

                if (running_cores == 0) {
                        // no need to worry about freeing memory
                        PyObject *uwsgi_dict = get_uwsgi_pydict("uwsgi");
                        if (uwsgi_dict) {
                                PyObject *ae = PyDict_GetItemString(uwsgi_dict, "atexit");
                                if (ae) {
                                        python_call(ae, PyTuple_New(0), 0, NULL);
                                }
                        }
                }
        } else {
                // If we stopped any watcher due to being out of async workers, restart it.
                int i = 0;
                struct uwsgi_socket *uwsgi_sock = uwsgi.sockets;
                for (; uwsgi_sock; uwsgi_sock = uwsgi_sock->next, ++i) {
                        PyObject *py_watcher_active = PyObject_GetAttrString(ugevent.watchers[i], "active");
                        if (py_watcher_active && PyBool_Check(py_watcher_active) &&
                            !PyInt_AsLong(py_watcher_active)) {
                            start_watcher(i, uwsgi_sock);
                        }
                        Py_XDECREF(py_watcher_active);
                }
        }

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


示例5: initc

void initc(void)
{
    PyObject *m = Py_InitModule3("c", c_funcs, "C repository types module");

    Empty_TUPLE = PyTuple_New(0);
    None_PAIR = PyTuple_Pack(2, Py_None, Py_None);

    _init_view(m);
    _init_repository(m);
    _init_container(m);
    _init_sequence(m);
    _init_db(m);
    _init_cursor(m);
    _init_env(m);
    _init_txn(m);
    _init_lock(m);
    _init_record(m);
    _init_store(m);

    PyExc_DBError = PyErr_NewException("chandlerdb.persistence.c.DBError",
                                       NULL, NULL);
    PyObject_SetAttrString(m, "DBError", PyExc_DBError);

    MAKE_EXC(m, DBLockDeadlockError, DBError);
    MAKE_EXC(m, DBLockNotGrantedError, DBError);
    MAKE_EXC(m, DBAccessError, DBError);
    MAKE_EXC(m, DBBusyError, DBError);
    MAKE_EXC(m, DBInvalidArgError, DBError);
    MAKE_EXC(m, DBNoSpaceError, DBError);
    MAKE_EXC(m, DBNotFoundError, DBError);
    MAKE_EXC(m, DBNoSuchFileError, DBError);
    MAKE_EXC(m, DBPermissionsError, DBError);
    MAKE_EXC(m, DBVersionMismatchError, DBError);
    MAKE_EXC(m, DBRunRecoveryError, DBError);

    PyModule_AddIntConstant(m, "DB_VERSION_MAJOR", DB_VERSION_MAJOR);
    PyModule_AddIntConstant(m, "DB_VERSION_MINOR", DB_VERSION_MINOR);
    PyModule_AddIntConstant(m, "DB_VERSION_PATCH", DB_VERSION_PATCH);

    if (!(m = PyImport_ImportModule("chandlerdb.util.c")))
        return;
    LOAD_FN(m, PyUUID_Check);
    LOAD_FN(m, PyUUID_Make16);
    LOAD_FN(m, _hash_bytes);
    LOAD_OBJ(m, Nil);
    LOAD_TYPE(m, CtxMgr);
    LOAD_TYPE(m, SkipList);
    SkipList_Node = (PyTypeObject *)
        PyObject_GetAttrString((PyObject *) SkipList, "Node");
    Py_DECREF(m);

    if (!(m = PyImport_ImportModule("chandlerdb.item.c")))
        return;
    LOAD_TYPE(m, CItem);
    LOAD_TYPE(m, ItemRef);
    LOAD_FN(m, CItem_getLocalAttributeValue);
    Py_DECREF(m);

    if (!(m = PyImport_ImportModule("chandlerdb.schema.c")))
        return;
    LOAD_FN(m, CAttribute_invokeAfterChange);
    Py_DECREF(m);
}
开发者ID:HackLinux,项目名称:chandler,代码行数:63,代码来源:c.c


示例6: DiscoDB_query

static PyObject *
DiscoDB_query(register DiscoDB *self, PyObject *query)
{
    PyObject
        *clause = NULL,
        *clauses = NULL,
        *literal = NULL,
        *literals = NULL,
        *iterclauses = NULL,
        *iterliterals = NULL,
        *negated = NULL,
        *pack = NULL,
        *term = NULL;
    struct ddb_query_clause *ddb_clauses = NULL;
    struct ddb_cursor *cursor = NULL;
    uint32_t
        i = 0,
        j = 0;

    clauses = PyObject_GetAttrString(query, "clauses");
    if (clauses == NULL)
        goto Done;

    iterclauses = PyObject_GetIter(clauses);
    if (iterclauses == NULL)
        goto Done;

    if ((i = PyObject_Length(clauses)) < 0)
        goto Done;
    ddb_clauses = ddb_query_clause_alloc(i);

    for (i = 0; (clause = PyIter_Next(iterclauses)); i++) {
        literals = PyObject_GetAttrString(clause, "literals");
        if (literals == NULL)
            goto Done;

        iterliterals = PyObject_GetIter(literals);
        if (iterliterals == NULL)
            goto Done;

        if ((j = PyObject_Length(literals)) < 0)
            goto Done;
        ddb_clauses[i].num_terms = j;
        ddb_clauses[i].terms     = ddb_query_term_alloc(j);

        for (j = 0; (literal = PyIter_Next(iterliterals)); j++) {
            negated = PyObject_GetAttrString(literal, "negated");
            if (negated == NULL)
                goto Done;

            term = PyObject_GetAttrString(literal, "term");
            if (term == NULL)
                goto Done;

            ddb_clauses[i].terms[j].not = PyObject_IsTrue(negated);

            pack = Py_BuildValue("(O)", term);
            if (pack == NULL)
                goto Done;

            if (!PyArg_ParseTuple(pack, "s#",
                                  &ddb_clauses[i].terms[j].key.data,
                                  &ddb_clauses[i].terms[j].key.length))
                goto Done;

            Py_CLEAR(literal);
            Py_CLEAR(negated);
            Py_CLEAR(pack);
            Py_CLEAR(term);
        }

        Py_CLEAR(clause);
        Py_CLEAR(literals);
        Py_CLEAR(iterliterals);
    }

    cursor = ddb_query(self->discodb, ddb_clauses, i);
    if (cursor == NULL)
        if (ddb_has_error(self->discodb))
            goto Done;

 Done:
    Py_CLEAR(clause);
    Py_CLEAR(clauses);
    Py_CLEAR(literal);
    Py_CLEAR(literals);
    Py_CLEAR(iterclauses);
    Py_CLEAR(iterliterals);
    Py_CLEAR(negated);
    Py_CLEAR(pack);
    Py_CLEAR(term);
    ddb_query_clause_dealloc(ddb_clauses, i);

    if (PyErr_Occurred()) {
        ddb_cursor_dealloc(cursor);
        return NULL;
    }

    return DiscoDBIter_new(&DiscoDBIterEntryType, self, cursor);
}
开发者ID:christofd,项目名称:disco,代码行数:100,代码来源:discodbmodule.c


示例7: RM_cmd

int RM_cmd(int args, char** argv) {
	printf("Ross-MacDonald\n");

	size_t const NB_ARGS = 12;

	PyObject *pName, *pModule, *pFunc;
	PyObject *pArgs, *pValue;

	if (args < NB_ARGS) {
		fprintf(stderr, "Not enough arguments\n");
		return -1;
	} else if (strcmp("rm", argv[0]) != 0) {
		fprintf(stderr, "Incorrect call\n");
		return -1;
	}

	Py_Initialize();

	PyRun_SimpleString("import sys, os");
	PyRun_SimpleString("sys.path.append('models')");

	pName = PyString_FromString("RM");

	pModule = PyImport_Import(pName);
	Py_DECREF(pName);

	if (pModule != NULL) {
		pFunc = PyObject_GetAttrString(pModule, "main");

		if (pFunc && PyCallable_Check(pFunc)) {
			pArgs = PyTuple_New(NB_ARGS - 1);

			for (int i = 0; i < NB_ARGS; ++i) {
				pValue = PyFloat_FromDouble(atof(argv[i]));
				if (!pValue) {
					Py_DECREF(pArgs);
					Py_DECREF(pModule);
					fprintf(stderr, "Error arguments\n");
					return -1;
				}
				PyTuple_SetItem(pArgs, i-1, pValue);
			}

			pValue = PyObject_CallObject(pFunc, pArgs);
			Py_DECREF(pArgs);
			if (pValue != NULL) {
				if (PyInt_AsLong(pValue) != 0) {
					printf("Call error\n");
				} else {
					printf("Call success\n");
				}
				Py_DECREF(pValue);
			}
			else {
				Py_DECREF(pFunc);
				Py_DECREF(pModule);
				PyErr_Print();
				fprintf(stderr,"Call failed\n");
				return -1;
			}
		}
		else {
			if (PyErr_Occurred())
				PyErr_Print();
			fprintf(stderr, "Cannot find function \"%s\"\n", argv[2]);
		}
		Py_XDECREF(pFunc);
		Py_DECREF(pModule);
	}

	else {
		PyErr_Print();
		fprintf(stderr, "Failed to load \"%s\"\n", argv[1]);
		return 1;
	}

	Py_Finalize();

	return 0;
}
开发者ID:pthevenet,项目名称:Epidemics,代码行数:80,代码来源:cli.c


示例8: PyErr_Format

//-------------------------------------------------------------------------------------
bool MethodDescription::checkArgs(PyObject* args)
{
	if (args == NULL || !PyTuple_Check(args))
	{
		PyErr_Format(PyExc_SystemError, "Method::checkArgs: method[%s] args is not a tuple.\n", 
			getName());

		PyErr_PrintEx(0);
		return false;
	}
	
	int offset = (isExposed() == true && g_componentType == CELLAPP_TYPE) ? 1 : 0;
	uint8 argsSize = argTypes_.size();
	uint8 giveArgsSize = PyTuple_Size(args);

	if (giveArgsSize != argsSize + offset)
	{
		PyErr_Format(PyExc_TypeError, "Method::checkArgs: method[%s] requires exactly %d argument%s; %d given", 
				getName(),
				argsSize,
				(argsSize == 1) ? "" : "s",
				PyTuple_Size(args));

		PyErr_PrintEx(0);
		return false;
	}	
	
	
	// 检查是否是一个exposed方法
	if(offset > 0)
	{
		PyObject* pyExposed = PyTuple_GetItem(args, 0);
		if (!PyLong_Check(pyExposed))
		{
			PyObject* pyeid = PyObject_GetAttrString(pyExposed, "id");
			if (pyeid == NULL || !PyLong_Check(pyeid))
			{
				Py_XDECREF(pyeid);
				PyErr_Format( PyExc_TypeError,
					"Method::checkArgs: method[%s] requires None, an id, or an object with an "
					"id as its first agument", getName());

				PyErr_PrintEx(0);
				return false;
			}
			
			Py_DECREF(pyeid);
		}
	}	
	
	for(uint8 i=0; i <argsSize; i++)
	{
		PyObject* pyArg = PyTuple_GetItem(args, i + offset);
		if (!argTypes_[i]->isSameType(pyArg))
		{
			PyObject* pExample = argTypes_[i]->parseDefaultStr("");
			PyErr_Format(PyExc_TypeError,
				"Method::checkArgs: method[%s] argument %d: Expected %s, %s found",
				getName(),
				i+1,
				pExample->ob_type->tp_name,
				pyArg != NULL ? pyArg->ob_type->tp_name : "NULL");
			
			PyErr_PrintEx(0);
			Py_DECREF(pExample);
			return false;
		}
	}	
	return true;
}
开发者ID:sdsgwangpeng,项目名称:kbengine,代码行数:71,代码来源:method.cpp


示例9: microprotocols_adapt

PyObject *
microprotocols_adapt(PyObject *obj, PyObject *proto, PyObject *alt)
{
    PyObject *adapter, *adapted, *key, *meth;
    char buffer[256];

    /* we don't check for exact type conformance as specified in PEP 246
       because the ISQLQuote type is abstract and there is no way to get a
       quotable object to be its instance */

    Dprintf("microprotocols_adapt: trying to adapt %s",
        Py_TYPE(obj)->tp_name);

    /* look for an adapter in the registry */
    if (!(key = PyTuple_Pack(2, Py_TYPE(obj), proto))) { return NULL; }
    adapter = PyDict_GetItem(psyco_adapters, key);
    Py_DECREF(key);
    if (adapter) {
        adapted = PyObject_CallFunctionObjArgs(adapter, obj, NULL);
        return adapted;
    }

    /* try to have the protocol adapt this object*/
    if ((meth = PyObject_GetAttrString(proto, "__adapt__"))) {
        adapted = PyObject_CallFunctionObjArgs(meth, obj, NULL);
        Py_DECREF(meth);
        if (adapted && adapted != Py_None) return adapted;
        Py_XDECREF(adapted);
        if (PyErr_Occurred()) {
            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
               PyErr_Clear();
            } else {
                return NULL;
            }
        }
    }
    else {
        /* proto.__adapt__ not found. */
        PyErr_Clear();
    }

    /* then try to have the object adapt itself */
    if ((meth = PyObject_GetAttrString(obj, "__conform__"))) {
        adapted = PyObject_CallFunctionObjArgs(meth, proto, NULL);
        Py_DECREF(meth);
        if (adapted && adapted != Py_None) return adapted;
        Py_XDECREF(adapted);
        if (PyErr_Occurred()) {
            if (PyErr_ExceptionMatches(PyExc_TypeError)) {
               PyErr_Clear();
            } else {
                return NULL;
            }
        }
    }
    else {
        /* obj.__conform__ not found. */
        PyErr_Clear();
    }

    /* Finally check if a superclass can be adapted and use the same adapter. */
    if (!(adapter = _get_superclass_adapter(obj, proto))) {
        return NULL;
    }
    if (Py_None != adapter) {
        adapted = PyObject_CallFunctionObjArgs(adapter, obj, NULL);
        return adapted;
    }

    /* else set the right exception and return NULL */
    PyOS_snprintf(buffer, 255, "can't adapt type '%s'",
        Py_TYPE(obj)->tp_name);
    psyco_set_error(ProgrammingError, NULL, buffer);
    return NULL;
}
开发者ID:gencer,项目名称:psycopg2,代码行数:75,代码来源:microprotocols.c


示例10: write_cb


//.........这里部分代码省略.........
            else // all iterations has been sent
            {
                stop=2;
            }    
        } 
        else if (PyFile_Check(cli->response_content) && (cli->response_content_obj==NULL)) // we treat file object
        {
            if (cli->response_iter_sent==-1) // we need to initialise the file descriptor
            {
                cli->response_fp=PyFile_AsFile(cli->response_content);
            }
            cli->response_iter_sent++;
            char buff[MAX_BUFF]="";  
            size_t len=fread(buff, sizeof(char), MAX_BUFF, cli->response_fp);
            if ((int)len==0)
            {
                stop=2;
            }
            else
            {
                if (write_cli(cli,buff, len, revents)==0)
                {
                    stop=2;
                }
                if ((int)len<MAX_BUFF)
                {
                    //we have send the whole file
                    stop=2;
                }
            }
            //free(buff);
        } 
        else if ((cli->response_content_obj!=NULL) && (PyIter_Check(cli->response_content_obj))) 
        {
            //we treat Iterator object
            cli->response_iter_sent++;
            PyObject *pyelem = cli->response_content;
            if (pyelem == NULL) 
            {
                stop = 2;
            }
            else 
            {
                char *buff;
#if (PY_VERSION_HEX < 0x02050000)
                int buflen;
                if (PyObject_AsReadBuffer(pyelem, (const void **) &buff, &buflen)==0)
#else
                Py_ssize_t buflen;
                if (PyObject_AsReadBuffer(pyelem, (const void **) &buff, &buflen)==0)
#endif
                {
                    // if this is a readable buffer, we send it. Other else, we ignore it.
                    if (write_cli(cli, buff, buflen, revents)==0)
                    {
                        stop=2;  //break the iterator loop
                    }
                }
                else
                {
                    printf("The item %i of your iterator is not a string!!!!  It will be skipped\n",cli->response_iter_sent);
                }
                Py_DECREF(pyelem);
                cli->response_content = PyIter_Next(cli->response_content_obj);
                if (cli->response_content==NULL)
                {
                     if (debug)
                     {
                         printf("host=%s,port=%i iterator ended uri=%s\n", cli->remote_addr, cli->remote_port, cli->uri );
                     }
                     stop=2;
                }
            }    
        } 
        else 
        {
            printf("wsgi output of is neither a list, neither a fileobject, neither an iterable object!!!!!\n");
            //PyErr_SetString(PyExc_TypeError, "Result must be a list, a fileobject or an iterable object");
            stop=1;
        }
    }// end of GET OR POST request
    if (stop==2)
    {
      if (cli->response_content!=NULL) {
        if (PyObject_HasAttrString(cli->response_content, "close"))
        {
            PyObject *pydummy=PyObject_GetAttrString(cli->response_content, "close");
            PyObject_CallFunction(pydummy, NULL);
            Py_DECREF(pydummy);
        }
      }
      ev_io_stop(EV_A_ w);
      close_connection(cli);
    }
    if (stop==1)
    {
        ev_io_stop(EV_A_ w);
        close_connection(cli);
    }
}
开发者ID:Amli,项目名称:fapws3,代码行数:101,代码来源:mainloop.c


示例11: update_environ

/*
The procedure call the Environ method called "method" and give pydict has parameter
*/
void update_environ(PyObject *pyenviron, PyObject *pydict, char *method)
{
    PyObject *pyupdate=PyObject_GetAttrString(pyenviron, method);
    PyObject_CallFunction(pyupdate, "(O)", pydict);
    Py_DECREF(pyupdate);
}
开发者ID:Amli,项目名称:fapws3,代码行数:9,代码来源:mainloop.c


示例12: not

/*
This is the main python handler that will transform and treat the client html request. 
return 1 if we have found a python object to treat the requested uri
return 0 if not (page not found)
return -1 in case of problem
return -2 in case the request command is not implemented
*/
int python_handler(struct client *cli)
{
    PyObject *pydict, *pydummy;
    int ret;

    if (debug)
         printf("host=%s,port=%i:python_handler:HEADER:\n%s**\n", cli->remote_addr, cli->remote_port, cli->input_header);
    //  1)initialise environ
    PyObject *pyenviron_class=PyObject_GetAttrString(py_base_module, "Environ");
    if (!pyenviron_class)
    {
         printf("load Environ failed from base module");
         exit(1);
    }
    PyObject *pyenviron=PyObject_CallObject(pyenviron_class, NULL);
    if (!pyenviron)
    {
         printf("Failed to create an instance of Environ");
         exit(1);
    }
    Py_DECREF(pyenviron_class);
    //  2)transform headers into a dictionary and send it to environ.update_headers
    pydict=header_to_dict(cli);
    if (pydict==Py_None)
    {
        Py_DECREF(pyenviron);
        return -500;
    }
    update_environ(pyenviron, pydict, "update_headers");
    Py_DECREF(pydict);   
    //  2bis) we check if the request method is supported
    PyObject *pysupportedhttpcmd = PyObject_GetAttrString(py_base_module, "supported_HTTP_command");
    if (cli->cmd==NULL) pydummy=Py_None; 
    else pydummy = PyString_FromString(cli->cmd);
    if (PySequence_Contains(pysupportedhttpcmd,pydummy)!=1)
    {
        //return not implemented 
        Py_DECREF(pysupportedhttpcmd);
        Py_DECREF(pydummy);
        Py_DECREF(pyenviron);
        return -501;
    }
    Py_DECREF(pydummy);
    //  2ter) we treat directly the OPTIONS command
    if (strcmp(cli->cmd,"OPTIONS")==0)
    {
        pydummy=PyString_FromFormat("HTTP/1.0 200 OK\r\nServer: %s\r\nAllow: ", VERSION) ;
        PyObject *pyitem; 
        int index, max;
        max = PyList_Size(pysupportedhttpcmd);
        for (index=0; index<max; index++)
        {
            pyitem=PyList_GetItem(pysupportedhttpcmd, index);  // no need to decref pyitem
            PyString_Concat(&pydummy, PyObject_Str(pyitem));
            if (index<max-1)
               PyString_Concat(&pydummy, PyString_FromString(", "));
        }
        PyString_Concat(&pydummy, PyString_FromString("\r\nContent-Length: 0\r\n\r\n"));
        cli->response_header = PyString_AsString(pydummy);
	cli->response_header_length=(int)PyString_Size(pydummy);
        cli->response_content=PyList_New(0);
        Py_DECREF(pyenviron);
        return 1;
    }
    Py_DECREF(pysupportedhttpcmd);
    //  3)find if the uri is registered
    if (handle_uri(cli)!=1)
    {
         if (py_generic_cb==NULL)
         {
            //printf("uri not found\n");
            Py_DECREF(pyenviron);
            return 0;
         }
         else
         {
             cli->wsgi_cb=py_generic_cb;
             Py_INCREF(cli->wsgi_cb);
             cli->uri_path=(char *)calloc(1, sizeof(char));
             strcpy(cli->uri_path,"");
         }
    }
    // 4) build path_info, ...
    pydict=py_build_method_variables(cli);
    update_environ(pyenviron, pydict, "update_uri");
    Py_DECREF(pydict);   
    // 5) in case of POST, put it into the wsgi.input
    if (strcmp(cli->cmd,"POST")==0)
    {
        ret=manage_header_body(cli, pyenviron);
        if (ret < 0) {
            return ret;
        }
//.........这里部分代码省略.........
开发者ID:Amli,项目名称:fapws3,代码行数:101,代码来源:mainloop.c


示例13: chunk_render

/* TODO triple check this to make sure reference counting is correct */
PyObject*
chunk_render(PyObject *self, PyObject *args) {
    RenderState state;

    int xoff, yoff;
    
    PyObject *imgsize, *imgsize0_py, *imgsize1_py;
    int imgsize0, imgsize1;
    
    PyObject *blocks_py;
    PyObject *left_blocks_py;
    PyObject *right_blocks_py;
    PyObject *up_left_blocks_py;
    PyObject *up_right_blocks_py;

    RenderModeInterface *rendermode;

    void *rm_data;
                
    PyObject *t = NULL;
    
    if (!PyArg_ParseTuple(args, "OOiiO",  &state.self, &state.img, &xoff, &yoff, &state.blockdata_expanded))
        return NULL;
    
    /* fill in important modules */
    state.textures = textures;
    state.chunk = chunk_mod;
    
    /* set up the render mode */
    rendermode = get_render_mode(&state);
    rm_data = calloc(1, rendermode->data_size);
    if (rendermode->start(rm_data, &state)) {
        free(rm_data);
        return Py_BuildValue("i", "-1");
    }

    /* get the image size */
    imgsize = PyObject_GetAttrString(state.img, "size");

    imgsize0_py = PySequence_GetItem(imgsize, 0);
    imgsize1_py = PySequence_GetItem(imgsize, 1);
    Py_DECREF(imgsize);

    imgsize0 = PyInt_AsLong(imgsize0_py);
    imgsize1 = PyInt_AsLong(imgsize1_py);
    Py_DECREF(imgsize0_py);
    Py_DECREF(imgsize1_py);


    /* get the block data directly from numpy: */
    blocks_py = PyObject_GetAttrString(state.self, "blocks");
    state.blocks = blocks_py;

    left_blocks_py = PyObject_GetAttrString(state.self, "left_blocks");
    state.left_blocks = left_blocks_py;

    right_blocks_py = PyObject_GetAttrString(state.self, "right_blocks");
    state.right_blocks = right_blocks_py;

    up_left_blocks_py = PyObject_GetAttrString(state.self, "up_left_blocks");
    state.up_left_blocks = up_left_blocks_py;

    up_right_blocks_py = PyObject_GetAttrString(state.self, "up_right_blocks");
    state.up_right_blocks = up_right_blocks_py;
    
    for (state.x = 15; state.x > -1; state.x--) {
        for (state.y = 0; state.y < 16; state.y++) {
            PyObject *blockid = NULL;
            
            /* set up the render coordinates */
            state.imgx = xoff + state.x*12 + state.y*12;
            /* 128*12 -- offset for z direction, 15*6 -- offset for x */
            state.imgy = yoff - state.x*6 + state.y*6 + 128*12 + 15*6;
            
            for (state.z = 0; state.z < 128; state.z++) {
                state.imgy -= 12;
		
		/* get blockid */
                state.block = getArrayByte3D(blocks_py, state.x, state.y, state.z);
                if (state.block == 0) {
                    continue;
                }
                
                /* make sure we're rendering inside the image boundaries */
                if ((state.imgx >= imgsize0 + 24) || (state.imgx <= -24)) {
                    continue;
                }
                if ((state.imgy >= imgsize1 + 24) || (state.imgy <= -24)) {
                    continue;
                }

                
                /* decref'd on replacement *and* at the end of the z for block */
                if (blockid) {
                    Py_DECREF(blockid);
                }
                blockid = PyInt_FromLong(state.block);

                // check for occlusion
//.........这里部分代码省略.........
开发者ID:Aurecanabis,项目名称:Minecraft-Overviewer,代码行数:101,代码来源:iterate.c


示例14: PyFile_GetLine

PyObject *
PyFile_GetLine(PyObject *f, int n)
{
    PyObject *result;

    if (f == NULL) {
        PyErr_BadInternalCall();
        return NULL;
    }

    {
        PyObject *reader;
        PyObject *args;

        reader = PyObject_GetAttrString(f, "readline");
        if (reader == NULL)
            return NULL;
        if (n <= 0)
            args = PyTuple_New(0);
        else
            args = Py_BuildValue("(i)", n);
        if (args == NULL) {
            Py_DECREF(reader);
            return NULL;
        }
        result = PyEval_CallObject(reader, args);
        Py_DECREF(reader);
        Py_DECREF(args);
        if (result != NULL && !PyBytes_Check(result) &&
            !PyUnicode_Check(result)) {
            Py_DECREF(result);
            result = NULL;
            PyErr_SetString(PyExc_TypeError,
                       "object.readline() returned non-string");
        }
    }

    if (n < 0 && result != NULL && PyBytes_Check(result)) {
        char *s = PyBytes_AS_STRING(result);
        Py_ssize_t len = PyBytes_GET_SIZE(result);
        if (len == 0) {
            Py_DECREF(result);
            result = NULL;
            PyErr_SetString(PyExc_EOFError,
                            "EOF when reading a line");
        }
        else if (s[len-1] == '\n') {
            if (result->ob_refcnt == 1)
                _PyBytes_Resize(&result, len-1);
            else {
                PyObject *v;
                v = PyBytes_FromStringAndSize(s, len-1);
                Py_DECREF(result);
                result = v;
            }
        }
    }
    if (n < 0 && result != NULL && PyUnicode_Check(result)) {
        Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
        Py_ssize_t len = PyUnicode_GET_SIZE(result);
        if (len == 0) {
            Py_DECREF(result);
            result = NULL;
            PyErr_SetString(PyExc_EOFError,
                            "EOF when reading a line");
        }
        else if (s[len-1] == '\n') {
            if (result->ob_refcnt == 1)
                PyUnicode_Resize(&result, len-1);
            else {
                PyObject *v;
                v = PyUnicode_FromUnicode(s, len-1);
                Py_DECREF(result);
                result = v;
            }
        }
    }
    return result;
}
开发者ID:Jimlan,项目名称:kbengine,代码行数:79,代码来源:fileobject.c


示例15: IterParser_init

/*
 * Initialize an IterParser object
 *
 * The Python arguments are:
 *
 *    *fd*: A Python file object or a callable object
 *    *buffersize*: The size of the read buffer
 */
static int
IterParser_init(IterParser *self, PyObject *args, PyObject *kwds)
{
    PyObject* fd              = NULL;
    PyObject* read            = NULL;
    ssize_t   buffersize      = 1 << 14;

    static char *kwlist[] = {"fd", "buffersize", NULL};
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:IterParser.__init__", kwlist,
                                     &fd, &buffersize)) {
        return -1;
    }

    /* Keep the buffersize within a reasonable range */
    self->buffersize = CLAMP(buffersize, (ssize_t)(1 << 10), (ssize_t)(1 << 24));
#ifdef __clang__
    /* Clang can't handle the file descriptors Python gives us,
       so in that case, we just call the object's read method. */
    read = PyObject_GetAttrString(fd, "read");
    if (read != NULL) {
        fd = read;
    }
#else
    self->file = PyObject_AsFileDescriptor(fd);
    if (self->file != -1) {
        /* This is a real C file handle or descriptor.  We therefore
           need to allocate our own read buffer, and get the real C
           object. */
        self->buffer = malloc((size_t)self->buffersize);
        if (self->buffer == NULL) {
            PyErr_SetString(PyExc_MemoryError, "Out of memory");
            goto fail;
        }
        self->fd = fd;   Py_INCREF(self->fd);
        lseek(self->file, 0, SEEK_SET);
    } else
#endif
    if (PyCallable_Check(fd)) {
        /* fd is a Python callable */
        self->fd = fd;   Py_INCREF(self->fd);
        self->read = fd; Py_INCREF(self->read);
    } else {
        PyErr_SetString(
            PyExc_TypeError,
            "Arg 1 to iterparser must be a file object or callable object");
        goto fail;
    }

    PyErr_Clear();

    self->queue_read_idx  = 0;
    self->queue_write_idx = 0;
    self->done            = 0;

    self->text = malloc((size_t)buffersize * sizeof(XML_Char));
    self->text_alloc = buffersize;
    if (self->text == NULL) {
        PyErr_SetString(PyExc_MemoryError, "Out of memory");
        goto fail;
    }
    text_clear(self);

    self->read_args = Py_BuildValue("(n)", buffersize);
    if (self->read_args == NULL) {
        goto fail;
    }

    self->dict_singleton = PyDict_New();
    if (self->dict_singleton == NULL) {
        goto fail;
    }

    self->td_singleton = PyUnicode_FromString("TD");
    if (self->td_singleton == NULL) {
        goto fail;
    }

    if (queue_realloc(self, buffersize)) {
        goto fail;
    }

    /* Set up an expat parser with our callbacks */
    self->parser = XML_ParserCreate(NULL);
    if (self->parser == NULL) {
        PyErr_SetString(PyExc_MemoryError, "Out of memory");
        goto fail;
    }
    XML_SetUserData(self->parser, self);
    XML_SetElementHandler(
        self->parser,
        (XML_StartElementHandler)startElement,
        (XML_EndElementHandler)endElement);
//.........这里部分代码省略.........
开发者ID:Juanlu001,项目名称:astropy,代码行数:101,代码来源:iterparse.c


示例16: initpympi


//.........这里部分代码省略.........
    /*   PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MAXLOC",
         PyInt_FromLong((long)MPI_MAXLOC)));*/
    reduceOpLookup[eMaxlocOp] = MPI_MAXLOC;
    PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"MAXLOC",
                PyInt_FromLong((long)eMaxlocOp)));

    PYCHECK(   PyString_ConcatFromString(&docString,"ANY_SOURCE: MPI_ANY_SOURCE (used for untargeted recv)\n"));
    PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"ANY_SOURCE",
                PyInt_FromLong((long)MPI_ANY_SOURCE)));

    PYCHECK(   PyString_ConcatFromString(&docString,"ANY_TAG: MPI_ANY_TAG (used for untargeted recv)\n"));
    PYCHECK(PyDict_SetItemString(PyMPI_dictionary,"ANY_TAG",
                PyInt_FromLong((long)MPI_ANY_TAG)));

    /* ----------------------------------------------- */
    /* We set up an internal communicator for PYTHON   */
    /* messaging and another for Python I/O            */
    /* ----------------------------------------------- */
    MPICHECK( MPI_COMM_WORLD,
            MPI_Comm_dup(MPI_COMM_WORLD,&PyMPI_COMM_WORLD));
    MPICHECK( MPI_COMM_WORLD,
            MPI_Comm_dup(MPI_COMM_WORLD,&PyMPI_COMM_INPUT));
    PYCHECK( PyString_ConcatFromString(&docString,"WORLD: Internal Python communicator\n") );
    PYCHECK( pyWorld = PyMPI_Comm(PyMPI_COMM_WORLD) );
    PYCHECK( PyDict_SetItemString(PyMPI_dictionary,"WORLD",pyWorld) );

    /* ----------------------------------------------- */
    /* Fetch member functions to appear as mpi.xxxx    */
    /* Make pyWorld immortal to avoid dealloc issues   */
    /* Magic Rating: 10/10                             */
    /* ----------------------------------------------- */
    Py_INCREF(pyWorld);
    for(methodPtr = PyMPIMethods_Comm; methodPtr->ml_name; ++methodPtr) {
        PYCHECK( member = PyObject_GetAttrString(pyWorld,methodPtr->ml_name) );
        Py_INCREF(member);
        PYCHECK( PyDict_SetItemString(PyMPI_dictionary,methodPtr->ml_name,member) );
    }

    /* ----------------------------------------------- */
    /* Set up the overloaded input                     */
    /* ----------------------------------------------- */
    PYCHECK( overloadedInput = PyMPI_File(worldRank != 0,PySys_GetObject("stdin"),PyMPI_COMM_INPUT) );
    Py_INCREF(overloadedInput);
    PyDict_SetItemString(PyMPI_dictionary,"stdin",overloadedInput);
    PySys_SetObject("stdin",overloadedInput);

    /* ----------------------------------------------- */
    /* Initial model is no output throttle             */
    /* ----------------------------------------------- */
    PYCHECK( PyMPI_UnrestrictedOutput(3) );

    /* ----------------------------------------------- */
    /* Have to set up some stuff for communicating     */
    /* arbitrary python objects                        */
    /* ----------------------------------------------- */

    /* -- set up PyMPI_pythonPickleType  -- */
    MPICHECKCOMMLESS( MPI_Type_contiguous(1,MPI_CHAR,&PyMPI_pythonPickleType) );
    MPICHECKCOMMLESS( MPI_Type_commit(&PyMPI_pythonPickleType) );
    Assert( PyMPI_pythonPickleType != MPI_CHAR );
    /* -- set up PyMPI_pythonFuncPickleType  -- */
    MPICHECKCOMMLESS( MPI_Type_contiguous(1,MPI_CHAR,&PyMPI_pythonFuncPickleType) );
    MPICHECKCOMMLESS( MPI_Type_commit(&PyMPI_pythonFuncPickleType) );
    Assert( PyMPI_pythonFuncPickleType != MPI_CHAR );

    /* -- set up PyMPI_pythonFuncPickleType  -- */< 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ PyObject_HEAD_INIT函数代码示例发布时间:2022-05-30
下一篇:
C++ PyObject_GetAttr函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap