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

C++ PyString_Check函数代码示例

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

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



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

示例1: init_uwsgi_app


//.........这里部分代码省略.........
    }

    if (wsgi_req->home_len) {
        set_dyn_pyhome(wsgi_req->home, wsgi_req->home_len);
    }

    if (wsgi_req->touch_reload_len > 0 && wsgi_req->touch_reload_len < 0xff) {
        struct stat trst;
        strncpy(wi->touch_reload, wsgi_req->touch_reload, wsgi_req->touch_reload_len);
        if (!stat(wi->touch_reload, &trst)) {
            wi->touch_reload_mtime = trst.st_mtime;
        }
    }

    wi->callable = up.loaders[loader](arg1);

    if (!wi->callable) {
        uwsgi_log("unable to load app %d (mountpoint='%s') (callable not found or import error)\n", id, wi->mountpoint);
        goto doh;
    }

    // the module contains multiple apps
    if (PyDict_Check((PyObject *)wi->callable)) {
        applications = wi->callable;
        uwsgi_log("found a multiapp module...\n");
        app_list = PyDict_Keys(applications);
        multiapp = PyList_Size(app_list);
        if (multiapp < 1) {
            uwsgi_log("you have to define at least one app in the apllications dictionary\n");
            goto doh;
        }

        PyObject *app_mnt = PyList_GetItem(app_list, 0);
        if (!PyString_Check(app_mnt)) {
            uwsgi_log("the app mountpoint must be a string\n");
            goto doh;
        }
        char *tmp_mountpoint = PyString_AsString(app_mnt);
        wi->mountpoint_len = strlen(wi->mountpoint) < 0xff ? strlen(wi->mountpoint) : (0xff-1);
        strncpy(wi->mountpoint, tmp_mountpoint, wi->mountpoint_len);
        wsgi_req->appid = wi->mountpoint;
        wsgi_req->appid_len = wi->mountpoint_len;
#ifdef UWSGI_DEBUG
        uwsgi_log("main mountpoint = %s\n", wi->mountpoint);
#endif
        wi->callable = PyDict_GetItem(applications, app_mnt);
        if (PyString_Check((PyObject *) wi->callable)) {
            PyObject *callables_dict = get_uwsgi_pydict((char *)arg1);
            if (callables_dict) {
                wi->callable = PyDict_GetItem(callables_dict, (PyObject *)wi->callable);
            }
        }
    }

    Py_INCREF((PyObject *)wi->callable);

    wi->environ = malloc(sizeof(PyObject*)*uwsgi.cores);
    if (!wi->environ) {
        uwsgi_error("malloc()");
        exit(1);
    }

    for(i=0; i<uwsgi.cores; i++) {
        wi->environ[i] = PyDict_New();
        if (!wi->environ[i]) {
            uwsgi_log("unable to allocate new env dictionary for app\n");
开发者ID:rascalmicro,项目名称:uwsgi,代码行数:67,代码来源:pyloader.c


示例2: addType

 bool addType(const char *name, PyObject *klass) {
   
   bool singleton = false;
   std::string desc;
   
   PyObject *sg = PyObject_GetAttrString(klass, "Singleton");
   if (!sg) {
     PyErr_Clear();
   } else {
     if (PyBool_Check(sg)) {
       singleton = (sg == Py_True);
     }
     Py_DECREF(sg);
   }
   
   PyObject *de = PyObject_GetAttrString(klass, "Description");
   if (!de) {
     PyErr_Clear();
   } else {
     if (PyString_Check(de)) {
       desc = PyString_AsString(de);
     }
     Py_DECREF(de);
   }
   
   PyObject *mt = PyObject_GetAttrString(klass, "Methods");
   
   if (!mt || !PyDict_Check(mt)) {
     std::cout << "pyloader: Missing \"Methods\" class member" << std::endl;
     Py_XDECREF(mt);
     return false;
   }
   
   if (PyDict_Size(mt) == 0) {
     std::cout << "pyloader: No keys in \"Methods\" dict" << std::endl;
     Py_DECREF(mt);
     return false;
   }
   
   lwc::MethodsTable *typeMethods = 0;
   
   PyObject *key;
   PyObject *value;
   Py_ssize_t pos = 0;
   
   while (PyDict_Next(mt, &pos, &key, &value)) {
     
     if (!PyString_Check(key) || !PyTuple_Check(value)) {
       std::cout << "pyloader: \"Methods\" must be a dict of tuples" << std::endl;
       continue;
     }
     
     bool add = true;
     char *mname = PyString_AsString(key);
     char *mdesc = NULL;
     
     long n = PyTuple_Size(value);
     if (n < 1 || n > 2) {
       std::cout << "pyloader: \"Methods\" dict values must be tuples with 1 to 2 elements" << std::endl;
       continue;
     }
     
     PyObject *args = PyTuple_GetItem(value, 0);
     if (!PyList_Check(args)) {
       std::cout << "pyloader: \"Methods\" dict values' tuple first element must be a list" << std::endl;
       continue;
     }
     
     if (n == 2) {
       PyObject *pdesc = PyTuple_GetItem(value, 1);
       if (!PyString_Check(pdesc)) {
         std::cout << "pyloader: \"Methods\" dict values' tuple second element must be a string" << std::endl;
         continue;
       }
       mdesc = PyString_AsString(pdesc);
     }
     
     lwc::Method meth;
     
     if (mdesc) {
       meth.setDescription(mdesc);
     }
     
     n = PyList_Size(args);
     
     for (long i=0; i<n; ++i) {
       PyObject *arg = PyList_GetItem(args, i);
       Py_ssize_t ts = PyTuple_Size(arg);
       if (!PyTuple_Check(arg) || ts < 2 || ts > 6) {
         std::cout << "pyloader: Arguments must be tuples with 2 to 6 elements" << std::endl;
         add = false;
         break;
       }
       lwc::Argument a;
       a.setDir(lwc::Direction(PyInt_AsLong(PyTuple_GetItem(arg, 0))));
       a.setType(lwc::Type(PyInt_AsLong(PyTuple_GetItem(arg, 1))));
       if (ts >= 3) {
         a.setArraySizeArg(PyInt_AsLong(PyTuple_GetItem(arg, 2)));
       }
       if (ts >= 4) {
//.........这里部分代码省略.........
开发者ID:gatgui,项目名称:lwc,代码行数:101,代码来源:pyloader.cpp


示例3: PyErr_LDB_OR_RAISE

/*
  convert a python string to a DRSUAPI drsuapi_DsReplicaAttribute attribute
 */
static PyObject *py_dsdb_DsReplicaAttribute(PyObject *self, PyObject *args)
{
	PyObject *py_ldb, *el_list, *ret;
	struct ldb_context *ldb;
	char *ldap_display_name;
	const struct dsdb_attribute *a;
	struct dsdb_schema *schema;
	struct dsdb_syntax_ctx syntax_ctx;
	struct ldb_message_element *el;
	struct drsuapi_DsReplicaAttribute *attr;
	TALLOC_CTX *tmp_ctx;
	WERROR werr;
	Py_ssize_t i;

	if (!PyArg_ParseTuple(args, "OsO", &py_ldb, &ldap_display_name, &el_list)) {
		return NULL;
	}

	PyErr_LDB_OR_RAISE(py_ldb, ldb);

	schema = dsdb_get_schema(ldb, NULL);
	if (!schema) {
		PyErr_SetString(PyExc_RuntimeError, "Failed to find a schema from ldb");
		return NULL;
	}

	a = dsdb_attribute_by_lDAPDisplayName(schema, ldap_display_name);
	if (a == NULL) {
		PyErr_Format(PyExc_KeyError, "Failed to find attribute '%s'", ldap_display_name);
		return NULL;
	}

	dsdb_syntax_ctx_init(&syntax_ctx, ldb, schema);
	syntax_ctx.is_schema_nc = false;

	tmp_ctx = talloc_new(ldb);
	if (tmp_ctx == NULL) {
		PyErr_NoMemory();
		return NULL;
	}

	/* If we were not given an LdbMessageElement */
	if (!PyList_Check(el_list)) {
		if (!py_check_dcerpc_type(el_list, "ldb", "MessageElement")) {
			PyErr_SetString(py_ldb_get_exception(),
					"list of strings or ldb MessageElement object required");
			return NULL;
		}
		/*
		 * NOTE:
		 * el may not be a valid talloc context, it
		 * could be part of an array
		 */
		el = pyldb_MessageElement_AsMessageElement(el_list);
	} else {
		el = talloc_zero(tmp_ctx, struct ldb_message_element);
		if (el == NULL) {
			PyErr_NoMemory();
			talloc_free(tmp_ctx);
			return NULL;
		}

		el->name = ldap_display_name;
		el->num_values = PyList_Size(el_list);

		el->values = talloc_array(el, struct ldb_val, el->num_values);
		if (el->values == NULL) {
			PyErr_NoMemory();
			talloc_free(tmp_ctx);
			return NULL;
		}

		for (i = 0; i < el->num_values; i++) {
			PyObject *item = PyList_GetItem(el_list, i);
			if (!PyString_Check(item)) {
				PyErr_Format(PyExc_TypeError, "ldif_elements should be strings");
				talloc_free(tmp_ctx);
				return NULL;
			}
			el->values[i].data = (uint8_t *)PyString_AsString(item);
			el->values[i].length = PyString_Size(item);
		}
	}

	attr = talloc_zero(tmp_ctx, struct drsuapi_DsReplicaAttribute);
	if (attr == NULL) {
		PyErr_NoMemory();
		talloc_free(tmp_ctx);
		return NULL;
	}

	werr = a->syntax->ldb_to_drsuapi(&syntax_ctx, a, el, attr, attr);
	PyErr_WERROR_NOT_OK_RAISE(werr);

	ret = py_return_ndr_struct("samba.dcerpc.drsuapi", "DsReplicaAttribute", attr, attr);

	talloc_free(tmp_ctx);
//.........这里部分代码省略.........
开发者ID:GSam,项目名称:samba,代码行数:101,代码来源:pydsdb.c


示例4: TRACEBACK_FETCH_ERROR

QString QgsPythonUtilsImpl::getTraceback()
{
#define TRACEBACK_FETCH_ERROR(what) {errMsg = what; goto done;}

  // acquire global interpreter lock to ensure we are in a consistent state
  PyGILState_STATE gstate;
  gstate = PyGILState_Ensure();

  QString errMsg;
  QString result;

  PyObject *modStringIO = NULL;
  PyObject *modTB = NULL;
  PyObject *obStringIO = NULL;
  PyObject *obResult = NULL;

  PyObject *type, *value, *traceback;

  PyErr_Fetch( &type, &value, &traceback );
  PyErr_NormalizeException( &type, &value, &traceback );

  modStringIO = PyImport_ImportModule( "cStringIO" );
  if ( modStringIO == NULL )
    TRACEBACK_FETCH_ERROR( "can't import cStringIO" );

  obStringIO = PyObject_CallMethod( modStringIO, ( char* ) "StringIO", NULL );

  /* Construct a cStringIO object */
  if ( obStringIO == NULL )
    TRACEBACK_FETCH_ERROR( "cStringIO.StringIO() failed" );

  modTB = PyImport_ImportModule( "traceback" );
  if ( modTB == NULL )
    TRACEBACK_FETCH_ERROR( "can't import traceback" );

  obResult = PyObject_CallMethod( modTB, ( char* ) "print_exception",
                                  ( char* ) "OOOOO",
                                  type, value ? value : Py_None,
                                  traceback ? traceback : Py_None,
                                  Py_None,
                                  obStringIO );

  if ( obResult == NULL )
    TRACEBACK_FETCH_ERROR( "traceback.print_exception() failed" );
  Py_DECREF( obResult );

  obResult = PyObject_CallMethod( obStringIO, ( char* ) "getvalue", NULL );
  if ( obResult == NULL )
    TRACEBACK_FETCH_ERROR( "getvalue() failed." );

  /* And it should be a string all ready to go - duplicate it. */
  if ( !PyString_Check( obResult ) )
    TRACEBACK_FETCH_ERROR( "getvalue() did not return a string" );

  result = PyString_AsString( obResult );

done:

  // All finished - first see if we encountered an error
  if ( result.isEmpty() && !errMsg.isEmpty() )
  {
    result = errMsg;
  }

  Py_XDECREF( modStringIO );
  Py_XDECREF( modTB );
  Py_XDECREF( obStringIO );
  Py_XDECREF( obResult );
  Py_XDECREF( value );
  Py_XDECREF( traceback );
  Py_XDECREF( type );

  // we are done calling python API, release global interpreter lock
  PyGILState_Release( gstate );

  return result;
}
开发者ID:AdamSaunders,项目名称:Quantum-GIS,代码行数:77,代码来源:qgspythonutilsimpl.cpp


示例5: ConvertPythonToRowset

RowSet *
ConvertPythonToRowset(PyObject * v)
{
    RowSet *pRow;
    Py_ssize_t row, col;
    int i, j;
    if (PyInt_Check(v)) {
        if (PyInt_AsLong(v) != 0)
            outputerrf(_("unexpected rowset error"));
        return NULL;
    }

    if (!PySequence_Check(v)) {
        outputerrf(_("invalid Python return"));
        return NULL;
    }

    row = PySequence_Size(v);
    col = 0;
    if (row > 0) {
        PyObject *cols = PySequence_GetItem(v, 0);
        if (!PySequence_Check(cols)) {
            outputerrf(_("invalid Python return"));
            return NULL;
        } else
            col = PySequence_Size(cols);
    }

    pRow = MallocRowset((size_t) row, (size_t) col);
    for (i = 0; i < (int) pRow->rows; i++) {
        PyObject *e = PySequence_GetItem(v, i);

        if (!e) {
            outputf(_("Error getting item %d\n"), i);
            continue;
        }

        if (PySequence_Check(e)) {
            for (j = 0; j < (int) pRow->cols; j++) {
                char buf[1024];
                PyObject *e2 = PySequence_GetItem(e, j);

                if (!e2) {
                    outputf(_("Error getting sub item (%d, %d)\n"), i, j);
                    continue;
                }
                if (PyUnicode_Check(e2))
                    strcpy(buf, PyString_AsString(PyUnicode_AsUTF8String(e2)));
                else if (PyString_Check(e2))
                    strcpy(buf, PyString_AsString(e2));
                else if (PyInt_Check(e2) || PyLong_Check(e2)
                         || !StrCaseCmp(e2->ob_type->tp_name, "Decimal"))       /* Not sure how to check for decimal type directly */
                    sprintf(buf, "%d", (int) PyInt_AsLong(e2));
                else if (PyFloat_Check(e2))
                    sprintf(buf, "%.4f", PyFloat_AsDouble(e2));
                else if (e2 == Py_None)
                    sprintf(buf, "[%s]", _("none"));
                else
                    sprintf(buf, "[%s]", _("unknown type"));

                SetRowsetData(pRow, (size_t) i, (size_t) j, buf);

                Py_DECREF(e2);
            }
        } else {
            outputf(_("Item %d is not a list\n"), i);
        }

        Py_DECREF(e);
    }
    return pRow;
}
开发者ID:alcacoop,项目名称:libgnubg-android,代码行数:72,代码来源:dbprovider.c


示例6: automaton_search_iter_set

static PyObject*
automaton_search_iter_set(PyObject* self, PyObject* args) {
	PyObject* object;
	PyObject* flag;
	ssize_t len;
	bool reset;

	// first argument - required string or buffer
	object = PyTuple_GetItem(args, 0);
	if (object) {
#ifdef PY3K
    #ifdef AHOCORASICK_UNICODE
        if (PyUnicode_Check(object))
            len = PyUnicode_GET_SIZE(object);
        else {
            PyErr_SetString(PyExc_TypeError, "string required");
            return NULL;
        }
    #else
        if (PyBytes_Check(object))
            len = PyBytes_GET_SIZE(object);
        else {
            PyErr_SetString(PyExc_TypeError, "string or bytes object required");
            return NULL;
        }
    #endif
#else
        if (PyString_Check(object)) {
            len = PyString_GET_SIZE(object);
        } else {
            PyErr_SetString(PyExc_TypeError, "string required 2");
            return NULL;
        }
#endif
	}
	else
		return NULL;

	// second argument - optional bool
	flag = PyTuple_GetItem(args, 1);
	if (flag) {
		switch (PyObject_IsTrue(flag)) {
			case 0:
				reset = false;
				break;
			case 1:
				reset = true;
				break;
			default:
				return NULL;
		}
	}
	else {
		PyErr_Clear();
		reset = false;
	}

	// update internal state
	Py_XDECREF(iter->object);
	Py_INCREF(object);
	iter->object	= object;
#ifdef AHOCORASICK_UNICODE
	iter->data = PyUnicode_AS_UNICODE(object);
#else
	iter->data = (uint8_t*)PyBytes_AS_STRING(object);
#endif

	if (!reset)
		iter->shift += (iter->index >= 0) ? iter->index : 0;

	iter->index		= -1;
	iter->end		= (int)len;

	if (reset) {
		iter->state  = iter->automaton->root;
		iter->shift  = 0;
		iter->output = NULL;
	}

	Py_RETURN_NONE;
}
开发者ID:pombredanne,项目名称:pyahocorasick,代码行数:81,代码来源:AutomatonSearchIter.c


示例7: PLy_traceback

/*
 * Extract a Python traceback from the current exception.
 *
 * The exception error message is returned in xmsg, the traceback in
 * tbmsg (both as palloc'd strings) and the traceback depth in
 * tb_depth.
 */
static void
PLy_traceback(char **xmsg, char **tbmsg, int *tb_depth)
{
	PyObject   *e,
			   *v,
			   *tb;
	PyObject   *e_type_o;
	PyObject   *e_module_o;
	char	   *e_type_s = NULL;
	char	   *e_module_s = NULL;
	PyObject   *vob = NULL;
	char	   *vstr;
	StringInfoData xstr;
	StringInfoData tbstr;

	/*
	 * get the current exception
	 */
	PyErr_Fetch(&e, &v, &tb);

	/*
	 * oops, no exception, return
	 */
	if (e == NULL)
	{
		*xmsg = NULL;
		*tbmsg = NULL;
		*tb_depth = 0;

		return;
	}

	PyErr_NormalizeException(&e, &v, &tb);

	/*
	 * Format the exception and its value and put it in xmsg.
	 */

	e_type_o = PyObject_GetAttrString(e, "__name__");
	e_module_o = PyObject_GetAttrString(e, "__module__");
	if (e_type_o)
		e_type_s = PyString_AsString(e_type_o);
	if (e_type_s)
		e_module_s = PyString_AsString(e_module_o);

	if (v && ((vob = PyObject_Str(v)) != NULL))
		vstr = PyString_AsString(vob);
	else
		vstr = "unknown";

	initStringInfo(&xstr);
	if (!e_type_s || !e_module_s)
	{
		if (PyString_Check(e))
			/* deprecated string exceptions */
			appendStringInfoString(&xstr, PyString_AsString(e));
		else
			/* shouldn't happen */
			appendStringInfoString(&xstr, "unrecognized exception");
	}
	/* mimics behavior of traceback.format_exception_only */
	else if (strcmp(e_module_s, "builtins") == 0
			 || strcmp(e_module_s, "__main__") == 0
			 || strcmp(e_module_s, "exceptions") == 0)
		appendStringInfo(&xstr, "%s", e_type_s);
	else
		appendStringInfo(&xstr, "%s.%s", e_module_s, e_type_s);
	appendStringInfo(&xstr, ": %s", vstr);

	*xmsg = xstr.data;

	/*
	 * Now format the traceback and put it in tbmsg.
	 */

	*tb_depth = 0;
	initStringInfo(&tbstr);
	/* Mimick Python traceback reporting as close as possible. */
	appendStringInfoString(&tbstr, "Traceback (most recent call last):");
	while (tb != NULL && tb != Py_None)
	{
		PyObject   *volatile tb_prev = NULL;
		PyObject   *volatile frame = NULL;
		PyObject   *volatile code = NULL;
		PyObject   *volatile name = NULL;
		PyObject   *volatile lineno = NULL;
		PyObject   *volatile filename = NULL;

		PG_TRY();
		{
			lineno = PyObject_GetAttrString(tb, "tb_lineno");
			if (lineno == NULL)
				elog(ERROR, "could not get line number from Python traceback");
//.........这里部分代码省略.........
开发者ID:codership,项目名称:postgres,代码行数:101,代码来源:plpy_elog.c


示例8: noteq_init

static PyObject *cboodle_init(PyObject *self, PyObject *args)
{
    char *devname = NULL;
    int ratewanted = 0;
    int verbose = 0;
    int ix, res;
    PyObject *extras = NULL;
    extraopt_t *opts = NULL;
    extraopt_t dummyopt = {NULL, NULL};

    if (!PyArg_ParseTuple(args, "|ziiO:init", &devname, &ratewanted, &verbose, &extras))
        return NULL;

    res = noteq_init();
    if (!res) {
        PyErr_SetString(PyExc_IOError, "unable to initialize note queue");
        return NULL;
    }

    if (extras && PyList_Check(extras)) {
        int count = PyList_Size(extras);

        opts = (extraopt_t *)malloc(sizeof(extraopt_t) * (count+1));
        if (!opts) {
            PyErr_SetString(PyExc_IOError, "unable to initialize extra options");
            return NULL;
        }

        for (ix=0; ix<count; ix++) {
            PyObject *tup = PyList_GetItem(extras, ix);
            PyObject *tkey, *tval;
            if (!tup)
                return NULL;
            if (!PyTuple_Check(tup) || PyTuple_Size(tup) != 2) {
                PyErr_SetString(PyExc_TypeError, "extraopts must be a list of 2-tuples");
                return NULL;
            }

            tkey = PyTuple_GetItem(tup, 0);
            if (!tkey)
                return NULL;
            tval = PyTuple_GetItem(tup, 1);
            if (!tval)
                return NULL;
            if (!PyString_Check(tkey)
                    || !(tval == Py_None || PyString_Check(tval))) {
                PyErr_SetString(PyExc_TypeError, "extraopts must be (string, string) or (string, None)");
                return NULL;
            }

            opts[ix].key = PyString_AsString(tkey);
            if (tval == Py_None)
                opts[ix].val = NULL;
            else
                opts[ix].val = PyString_AsString(tval);
        }

        opts[count].key = NULL;
        opts[count].val = NULL;
    }

    res = audev_init_device(devname, ratewanted, (verbose!=0),
                            (opts?opts:(&dummyopt)));
    if (!res) {
        PyErr_SetString(PyExc_IOError, "unable to initialize audio device");
        if (opts) {
            free(opts);
        }
        return NULL;
    }

    if (opts) {
        free(opts);
    }

    Py_INCREF(Py_None);
    return Py_None;
}
开发者ID:ziz,项目名称:boodler,代码行数:78,代码来源:cboodle.c


示例9: wrap_getattro

static PyObject *
wrap_getattro(PyObject *self, PyObject *name)
{
    PyObject *wrapped;
    PyObject *descriptor;
    PyObject *res = NULL;
    char *name_as_string;
    int maybe_special_name;

#ifdef Py_USING_UNICODE
    /* The Unicode to string conversion is done here because the
       existing tp_getattro slots expect a string object as name
       and we wouldn't want to break those. */
    if (PyUnicode_Check(name)) {
        name = PyUnicode_AsEncodedString(name, NULL, NULL);
        if (name == NULL)
            return NULL;
    }
    else
#endif
    if (!PyString_Check(name)){
        PyErr_SetString(PyExc_TypeError, "attribute name must be string");
        return NULL;
    }
    else
        Py_INCREF(name);

    name_as_string = PyString_AS_STRING(name);
    wrapped = Proxy_GET_OBJECT(self);
    if (wrapped == NULL) {
        PyErr_Format(PyExc_RuntimeError,
            "object is NULL; requested to get attribute '%s'",
            name_as_string);
        goto finally;
    }

    maybe_special_name = name_as_string[0] == '_' && name_as_string[1] == '_';

    if (!(maybe_special_name && strcmp(name_as_string, "__class__") == 0)) {

        descriptor = WrapperType_Lookup(self->ob_type, name);

        if (descriptor != NULL) {
            if (PyType_HasFeature(descriptor->ob_type, Py_TPFLAGS_HAVE_CLASS)
                && descriptor->ob_type->tp_descr_get != NULL) {
                res = descriptor->ob_type->tp_descr_get(
                        descriptor,
                        self,
                        (PyObject *)self->ob_type);
            } else {
                Py_INCREF(descriptor);
                res = descriptor;
            }
            goto finally;
        }
    }
    res = PyObject_GetAttr(wrapped, name);

finally:
    Py_DECREF(name);
    return res;
}
开发者ID:Andyvs,项目名称:TrackMonthlyExpenses,代码行数:62,代码来源:_zope_proxy_proxy.c


示例10: if


//.........这里部分代码省略.........
						break;
					}
					continue;
				}
				case celServiceEventProgressbar:
				{
					if (area.width() > 0 && isPlayable && service_info && !service_info->getEvent(*m_cursor, evt))
					{
						char buffer[15];
						snprintf(buffer, sizeof(buffer), "%d %%", (int)(100 * (now - evt->getBeginTime()) / evt->getDuration()));
						text = buffer;
						flags|=gPainter::RT_HALIGN_RIGHT;
						break;
					}
					continue;
				}
				}

				eRect tmp = area;
				int xoffs = 0;
				ePtr<gPixmap> piconPixmap;

				if (e == celServiceName)
				{
					//picon stuff
					if (isPlayable && PyCallable_Check(m_GetPiconNameFunc))
					{
						ePyObject pArgs = PyTuple_New(1);
						PyTuple_SET_ITEM(pArgs, 0, PyString_FromString(ref.toString().c_str()));
						ePyObject pRet = PyObject_CallObject(m_GetPiconNameFunc, pArgs);
						Py_DECREF(pArgs);
						if (pRet)
						{
							if (PyString_Check(pRet))
							{
								std::string piconFilename = PyString_AS_STRING(pRet);
								if (!piconFilename.empty())
									loadPNG(piconPixmap, piconFilename.c_str());
							}
							Py_DECREF(pRet);
						}
					}
					xoffs = xoffset;
					tmp.setWidth(((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? tmp.width() : m_column_width) - xoffs);
				}

				eTextPara *para = new eTextPara(tmp);
				para->setFont(m_element_font[e]);
				para->renderString(text.c_str());

				if (e == celServiceName)
				{
					eRect bbox = para->getBoundBox();

					int servicenameWidth = ((!isPlayable || m_column_width == -1 || (!piconPixmap && !m_column_width)) ? bbox.width() : m_column_width);
					m_element_position[celServiceInfo].setLeft(area.left() + servicenameWidth + m_items_distances + xoffs);
					m_element_position[celServiceInfo].setTop(area.top());
					m_element_position[celServiceInfo].setWidth(area.width() - (servicenameWidth + m_items_distances + xoffs));
					m_element_position[celServiceInfo].setHeight(area.height());

					if (isPlayable)
					{
						//picon stuff
						if (PyCallable_Check(m_GetPiconNameFunc) and (m_column_width || piconPixmap))
						{
							eRect area = m_element_position[celServiceInfo];
开发者ID:Tsakman,项目名称:enigma2,代码行数:67,代码来源:listboxservice.cpp


示例11: call_python_function

static LIST*
call_python_function(RULE* r, FRAME* frame)
{
    LIST* result = 0;
    PyObject* arguments = PyTuple_New(frame->args->count);
    int i ;
    PyObject* py_result;

    for(i = 0; i < frame->args->count; ++i)
    {
        PyObject* arg = PyList_New(0);
        LIST* l = lol_get( frame->args, i);

        for(; l; l = l->next)
        {
            PyObject* v = PyString_FromString(l->string);
            /* Steals reference to 'v' */
            PyList_Append(arg, v);            
        }
        /* Steals reference to 'arg' */
        PyTuple_SetItem(arguments, i, arg);
    }

    py_result = PyObject_CallObject(r->python_function, arguments);
    Py_DECREF(arguments);
    if (py_result != NULL) {
        
        if (PyList_Check(py_result)) {
            int size = PyList_Size(py_result);
            int i;
            for(i = 0; i < size; ++i)
            {
                PyObject* item = PyList_GetItem(py_result, i);
                if (PyString_Check(item))
                {
                    result = list_new(result, 
                                      newstr(PyString_AsString(item)));
                }
                else
                {
                    fprintf(stderr, "Non-string object returned by Python call\n");
                }
            }
        }
        else if (PyInstance_Check(py_result))
        {
            static char instance_name[1000];
            static char imported_method_name[1000];
            module_t* m;
            PyObject* method;
            PyObject* method_name = PyString_FromString("foo");
            RULE* r;

            fprintf(stderr, "Got instance!\n");

            snprintf(instance_name, 1000,
                     "pyinstance%d", python_instance_number);
            snprintf(imported_method_name, 1000,
                     "pyinstance%d.foo", python_instance_number);
            ++python_instance_number;
            
            m = bindmodule(instance_name);

            /* This is expected to get bound method. */
            method = PyObject_GetAttr(py_result, method_name);
            
            r = bindrule( imported_method_name, root_module() );

            r->python_function = method;

            result = list_new(0, newstr(instance_name));    

            Py_DECREF(method_name);
        }
        else if (py_result == Py_None)
        {
            result = L0;
        }
        else
        {
            fprintf(stderr, "Non-list object returned by Python call\n");
        }

        Py_DECREF(py_result);
    }
    else {
        PyErr_Print();
        fprintf(stderr,"Call failed\n");
    }
    
    return result;
}
开发者ID:Albermg7,项目名称:boost,代码行数:92,代码来源:compile.c


示例12: exceptionlist__initmodule

int
exceptionlist__initmodule(PyObject* module, struct exceptionlist* exclist) {
	const struct exceptionlist* exc;
	char* longname = NULL;
	PyObject* name;
	Py_ssize_t size;
	Py_ssize_t maxsize;

	if ((name = PyObject_GetAttrString(module, "__name__")) == NULL)
		return -1;
	if (!PyString_Check(name)) {
		PyErr_SetString(PyExc_TypeError, "__name__ required an str()");
		goto failed;
	}
	size = PyString_GET_SIZE(name);
	for (maxsize = 0, exc = exclist; exc->exc_name != NULL; exc++) {
		register int i = strlen(exc->exc_name);
		if (i > maxsize)
			maxsize = i;
	}
	if ((longname = PyMem_MALLOC(size + sizeof(".") + maxsize + sizeof("\0"))) == NULL) {
		PyErr_NoMemory();
		goto failed;
	}
	memcpy(longname, PyString_AS_STRING(name), size);
	Py_DECREF(name);
	longname[size++] = '.';
	for (exc = exclist; exc->exc_name != NULL; exc++) {
		PyObject* dict;
		PyObject* s;
		
		if ((dict = PyDict_New()) == NULL)
			goto failed;
		if ((s = PyString_FromString(exc->exc_doc)) == NULL) {
			Py_DECREF(dict);
			goto failed;
		}
		if (PyDict_SetItemString(dict, "__doc__", s) < 0) {
			Py_DECREF(dict);
			Py_DECREF(s);
			goto failed;
		}
		Py_DECREF(s);
		strcpy(&longname[size], exc->exc_name);
		if (*exc->exc_this == NULL &&
		   (*exc->exc_this = PyErr_NewException(longname, *exc->exc_base, dict)) == NULL) {
			Py_DECREF(dict);
			goto failed;
		}
		Py_DECREF(dict);
	}
	PyMem_FREE(longname);
	for (exc = exclist; exc->exc_name != NULL; exc++) {
		Py_INCREF(*exc->exc_this);
		if (PyModule_AddObject(module, exc->exc_name, *exc->exc_this) < 0)
			return -1;
	}
	return 0;
failed:
	if (longname != NULL)
		PyMem_FREE(longname);
	Py_DECREF(name);
	return -1;
}
开发者ID:grossho,项目名称:billow,代码行数:64,代码来源:pyexceptionlist.c


示例13: from_python

dbtype_t
from_python(pgctx_t *ctx, PyObject *ob)
{
    dbtype_t db;
    char *buf;
    Py_ssize_t length;
    PyObject *items;
    struct tm tm;
    long usec;
    //int i;
    
    if (PyObject_HasAttrString(ob, "__topongo__")) {
        ob = PyObject_CallMethod(ob, "__topongo__", NULL);
        if (PyErr_Occurred())
            return DBNULL;
    }
    if (ob == Py_None) {
        db = DBNULL;
    } else if (ob == pongo_id) {
        db = dbuuid_new(ctx, NULL);
    } else if (ob == pongo_utcnow) {
        db = dbtime_now(ctx);
    } else if (PyBool_Check(ob)) {
        db = dbboolean_new(ctx, ob == Py_True);
    } else if (PyInt_Check(ob)) {
        db = dbint_new(ctx, PyInt_AsLong(ob));
    } else if (PyLong_Check(ob)) {
        db = dbint_new(ctx, PyLong_AsLongLong(ob));
    } else if (PyFloat_Check(ob)) {
        db = dbfloat_new(ctx, PyFloat_AsDouble(ob));
    } else if (PyString_Check(ob)) {
        PyString_AsStringAndSize(ob, &buf, &length);
        // FIXME:
        //db = dbbuffer_new(ctx, buf, length);
        db = dbstring_new(ctx, buf, length);
    } else if (PyUnicode_Check(ob)) {
        ob = PyUnicode_AsUTF8String(ob);
        if (ob) {
            PyString_AsStringAndSize(ob, &buf, &length);
            db = dbstring_new(ctx, buf, length);
            Py_DECREF(ob);
        }
    } else if (PyDateTime_Check(ob)) {
        memset(&tm, 0, sizeof(tm));
        tm.tm_year = PyDateTime_GET_YEAR(ob);
        tm.tm_mon = PyDateTime_GET_MONTH(ob);
        tm.tm_mday = PyDateTime_GET_DAY(ob);
        tm.tm_hour = PyDateTime_DATE_GET_HOUR(ob);
        tm.tm_min = PyDateTime_DATE_GET_MINUTE(ob);
        tm.tm_sec = PyDateTime_DATE_GET_SECOND(ob);
        usec = PyDateTime_DATE_GET_MICROSECOND(ob);
        tm.tm_year -= 1900;
        db = dbtime_newtm(ctx, &tm, usec);
#ifdef WANT_UUID_TYPE
    } else if (PyObject_TypeCheck(ob, uuid_class)) {
        ob = PyObject_CallMethod(ob, "get_bytes", NULL);
        PyString_AsStringAndSize(ob, &buf, &length);
        db = dbuuid_new(ctx, (uint8_t*)buf);
#endif
    } else if (Py_TYPE(ob) == &PongoList_Type) {
        // Resolve proxy types back to their original dbtype
        PongoList *p = (PongoList*)ob;
        db = p->dbptr;
    } else if (Py_TYPE(ob) == &PongoDict_Type) {
        // Resolve proxy types back to their original dbtype
        PongoDict *p = (PongoDict*)ob;
        db = p->dbptr;
    } else if (Py_TYPE(ob) == &PongoCollection_Type) {
        // Resolve proxy types back to their original dbtype
        PongoCollection *p = (PongoCollection*)ob;
        db = p->dbptr;
    } else if (PyMapping_Check(ob)) {
        length = PyMapping_Length(ob);
        items = PyMapping_Items(ob);
        if (items) {
            // mapping object implements "items"
            db = dbobject_new(ctx);
            dbobject_update(ctx, db, length, _py_mapping_cb, items, NOSYNC);
            Py_XDECREF(items);
        } else {
            // mapping object implements iterator protocol
            // don't have to decref the iterator object cuz it self-decrefs
            // upon StopIteration
            PyErr_Clear();
            items = PyObject_GetIter(ob);
            db = dbobject_new(ctx);
            dbobject_update(ctx, db, length, _py_itermapping_cb, items, NOSYNC);
        }
    } else if (PySequence_Check(ob)) {
        length = PySequence_Length(ob);
        db = dblist_new(ctx);
        dblist_extend(ctx, db, length, _py_sequence_cb, ob, NOSYNC);
    } else {
        // FIXME: Unknown object type
        PyErr_SetObject(PyExc_TypeError, (PyObject*)Py_TYPE(ob));
        db = DBNULL;
    }
    return db;
}
开发者ID:cfrantz,项目名称:pongo,代码行数:99,代码来源:pongo.c


示例14: JSONToObj

PyObject* JSONToObj(PyObject* self, PyObject *arg)
{
    PyObject *ret;
    PyObject *sarg;
    JSONObjectDecoder decoder = 
    {
        Object_newString,
        Object_newDateTime,
        Object_objectAddKey,
        Object_arrayAddItem,
        Object_newTrue,
        Object_newFalse,
        Object_newNull,
        Object_newObject,
        Object_newArray,
        Object_newInteger,
        Object_newLong,
        Object_newDouble,
        Object_releaseObject,
        PyObject_Malloc,
        PyObject_Free,
        PyObject_Realloc
    };

    if (PyString_Check(arg))
    {
        sarg = arg;
    }
    else
    if (PyUnicode_Check(arg))
    {
        sarg = PyUnicode_AsUTF8String(arg);
        if (sarg == NULL)
        {
            //Exception raised above us by codec according to docs
            return NULL;
        }
    }
    else
    {
        PyErr_Format(PyExc_TypeError, "Expected String or Unicode");
        return NULL;
    }

    decoder.errorStr = NULL;
    decoder.errorOffset = NULL;
    
    ret = JSON_DecodeObject(&decoder, PyString_AS_STRING(sarg), PyString_GET_SIZE(sarg)); 

    if (sarg != arg)
    {
        Py_DECREF(sarg);
    }

    if (decoder.errorStr)
    {
        /*
        FIXME: It's possible to give a much nicer error message here with actual failing element in input etc*/
        
        PyErr_Format (PyExc_ValueError, "%s", decoder.errorStr);
        
        if (ret)
        {
            Py_DECREF( (PyObject *) ret);
        }
        
        return NULL;
    }
    
    return ret;
}
开发者ID:pelletier,项目名称:ultrajson,代码行数:71,代码来源:JSONtoObj.c


示例15: LPX_init

static int LPX_init(LPXObject *self, PyObject *args, PyObject *kwds)
{
	char *mps_n=NULL, *freemps_n=NULL, *cpxlp_n=NULL;
	PyObject *model_obj=NULL;
	static char *kwlist[] = {"gmp","mps","freemps","cpxlp",NULL};
	if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Osss", kwlist, &model_obj, &mps_n, &freemps_n, &cpxlp_n)) {
		return -1;
	}
	int numargs = (mps_n?1:0)+(freemps_n?1:0)+(cpxlp_n?1:0)+(model_obj?1:0);
	if (numargs>1) {
		PyErr_SetString(PyExc_TypeError, "cannot specify multiple data sources");
		return -1;
	}
	if (numargs==0) {
		// No arguments.  Create an empty problem.
		self->lp = glp_create_prob();
	} else {
		// Some of these are pretty straightforward data reading routines.
		if (mps_n) {
#if GLPK_VERSION(4, 29)
			self->lp = glp_create_prob();
			int failure = glp_read_mps(self->lp, GLP_MPS_DECK, NULL, mps_n);
			if (failure) {
				PyErr_SetString(PyExc_RuntimeError, "MPS reader failed");
				return -1;
			}
#else
			self->lp = lpx_read_mps(mps_n);
#endif
		} else if (freemps_n) {
#if GLPK_VERSION(4, 29)
			self->lp = glp_create_prob();
			int failure = glp_read_mps(self->lp, GLP_MPS_FILE, NULL, mps_n);
			if (failure) {
				PyErr_SetString(PyExc_RuntimeError, "Free MPS reader failed");
				return -1;
			}
#else
			self->lp = lpx_read_freemps(freemps_n);
#endif
		} else if (cpxlp_n) {
#if GLPK_VERSION(4, 29)
			self->lp = glp_create_prob();
			int failure = glp_read_lp(self->lp, NULL, mps_n);
			if (failure) {
				PyErr_SetString(PyExc_RuntimeError, "CPLEX LP reader failed");
				return -1;
			}
#else
			self->lp = lpx_read_cpxlp(cpxlp_n);
#endif
		} else if (model_obj) {
			// This one can take a few possible values.
			char *model[] = {NULL,NULL,NULL};
			if (PyString_Check(model_obj)) {
				// Single string object.
				model[0] = PyString_AsString(model_obj);
				if (!model[0])
					return -1;
			} else if (PyTuple_Check(model_obj)) {
				// Possibly module arguments.
				int i,size = PyTuple_Size(model_obj);
				if (size < -1)
					return -1;
				if (size >  3) {
					PyErr_SetString(PyExc_ValueError, "model tuple must have length<=3");
					return -1;
				}
				for (i=0; i < size; ++i) {
					PyObject *so = PyTuple_GET_ITEM(model_obj,i);
					if (so == Py_None)
						continue;
					model[i] = PyString_AsString(so);
					if (model[i] == NULL)
						return -1;
				}
			} else {
				PyErr_SetString(PyExc_TypeError, "model arg must be string or tuple");
				return -1;
			}
			// Now, pass in that information.
			if (!model[0])
				return -1;
			self->lp = lpx_read_model(model[0], model[1], model[2]);
		}
	}
	// Any of the methods above may have failed, so the LP would be null.
	if (LP == NULL) {
		PyErr_SetString(numargs ? PyExc_RuntimeError : PyExc_MemoryError, "could not create problem");
		return -1;
	}
	// Create those rows and cols and things.
	self->cols = (PyObject*)BarCol_New(self, 0);
	self->rows = (PyObject*)BarCol_New(self, 1);
	self->obj = (PyObject*)Obj_New(self);
#ifdef USEPARAMS
	self->params = (PyObject*)Params_New(self);
#endif
	return 0;
}
开发者ID:danielriosgarza,项目名称:pyglpk,代码行数:100,代码来源:lp.c


示例16: PyImport_ImportModule

char *PyTraceback_AsString(PyObject *exc_tb)
{
	const char *errMsg = NULL; /* holds a local error message */
	char *result = NULL; /* a valid, allocated result. */
	PyObject *modStringIO = NULL;
	PyObject *modTB = NULL;
	PyObject *obFuncStringIO = NULL;
	PyObject *obStringIO = NULL;
	PyObject *obFuncTB = NULL;
	PyObject *argsTB = NULL;
	PyObject *obResult = NULL;

#if PY_MAJOR_VERSION <= 2
	/* Import the modules we need - cStringIO and traceback */
	modStringIO = PyImport_ImportModule("cStringIO");
	if (modStringIO==NULL)
		TRACEBACK_FETCH_ERROR("cant import cStringIO\n");

	modTB = PyImport_ImportModule("traceback");
	if (modTB==NULL)
		TRACEBACK_FETCH_ERROR("cant import traceback\n");
	/* Construct a cStringIO object */
	obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO");
	if (obFuncStringIO==NULL)
		TRACEBACK_FETCH_ERROR("cant find cStringIO.StringIO\n");
	obStringIO = PyObject_CallObject(obFuncStringIO, NULL);
	if (obStringIO==NULL)
		TRACEBACK_FETCH_ERROR("cStringIO.StringIO() failed\n");
#else
	/* Import the modules we need - io and traceback */
	modStringIO = PyImport_ImportModule("io");
	if (modStringIO==NULL)
		TRACEBACK_FETCH_ERROR("cant import io\n");

	modTB = PyImport_ImportModule("traceback");
	if (modTB==NULL)
		TRACEBACK_FETCH_ERROR("cant import traceback\n");
	/* Construct a StringIO object */
	obFuncStringIO = PyObject_GetAttrString(modStringIO, "StringIO");
	if (obFuncStringIO==NULL)
		TRACEBACK_FETCH_ERROR("cant find io.StringIO\n");
	obStringIO = PyObject_CallObject(obFuncStringIO, NULL);
	if (obStringIO==NULL)
		TRACEBACK_FETCH_ERROR("io.StringIO() failed\n");
#endif
	/* Get the traceback.print_exception function, and call it. */
	obFuncTB = PyObject_GetAttrString(modTB, "print_tb");
	if (obFuncTB==NULL)
		TRACEBACK_FETCH_ERROR("cant find traceback.print_tb\n");

	argsTB = Py_BuildValue("OOO",
			exc_tb  ? exc_tb  : Py_None,
			Py_None,
			obStringIO);
	if (argsTB==NULL)
		TRACEBACK_FETCH_ERROR("cant make print_tb arguments\n");

	obResult = PyObject_CallObject(obFuncTB, argsTB);
	if (obResult==NULL)
		TRACEBACK_FETCH_ERROR("traceback.print_tb() failed\n");
	/* Now call the getvalue() method in the StringIO instance */
	Py_DECREF(obFuncStringIO);
	obFuncStringIO = PyObject_GetAttrString(obStringIO, "getvalue");
	if (obFuncStringIO==NULL)
		TRACEBACK_FETCH_ERROR("cant find getvalue function\n");
	Py_DECREF(obResult);
	obResult = PyObject_CallObject(obFuncStringIO, NULL);
	if (obResult==NULL)
		TRACEBACK_FETCH_ERROR("getvalue() failed.\n");

	/* And it should be a string all ready to go - duplicate it. */
#if PY_MAJOR_VERSION <= 2
	if (!PyString_Check(obResult))
#else
	if (!PyUnicode_Check(obResult))
#endif
			TRACEBACK_FETCH_ERROR("getvalue() did not return a string\n");

	{ // a temp scope so I can use temp locals.
#if PY_MAJOR_VERSION <= 2
	char *tempResult = PyString_AsString(obResult);
#else
	char *tempResult = PyUnicode_AsUTF8(obResult);
#endif
	result = (char *)PyMem_Malloc(strlen(tempResult)+1);
	if (result==NULL)
		TRACEBACK_FETCH_ERROR("memory error duplicating the traceback string\n");

	strcpy(result, tempResult);
	} // end of temp scope.
done:
	/* All finished - first see if we encountered an error */
	if (result==NULL && errMsg != NULL) {
		result = (char *)PyMem_Malloc(strlen(errMsg)+1);
		if (result != NULL)
			/* if it does, not much we can do! */
			strcpy(result, errMsg);
	}
	Py_XDECREF(modStringIO);
	Py_XDECREF(modTB);
//.........这里部分代码省略.........
开发者ID:svn2github,项目名称:virtualbox,代码行数:101,代码来源:ErrorUtils.cpp


示例17: PyString_Format


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
C++ PyString_FromFormat函数代码示例发布时间:2022-05-30
下一篇:
C++ PyString_AsStringAndSize函数代码示例发布时间: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