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

C++ PyList_Append函数代码示例

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

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



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

示例1: PyList_New

static PyObject *parse_qs(PyObject *self, PyObject *args, PyObject *kw)
{

    PyObject *pairs, *dict;
    int i, n, len, lsize;
    char *qs;
    int keep_blank_values = 0;
    int strict_parsing = 0; /* XXX not implemented */
    char *keywords[] = { "qs", "keep_blank_values", "strict_parsing", 0 };
    
    if (! PyArg_ParseTupleAndKeywords(args, kw, "s|ii", keywords, &qs, &keep_blank_values, 
                           &strict_parsing)) 
        return NULL; /* error */

    /* split query string by '&' and ';' into a list of pairs */
    /* PYTHON 2.5: 'PyList_New' uses Py_ssize_t for input parameters */ 
    pairs = PyList_New(0);
    if (pairs == NULL)
        return NULL;

    i = 0;
    len = strlen(qs);

    while (i < len) {

        PyObject *pair;
        char *cpair;
        int j = 0;

        /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ 
        pair = PyString_FromStringAndSize(NULL, len);
        if (pair == NULL)
            return NULL;

        /* split by '&' or ';' */
        cpair = PyString_AS_STRING(pair);
        while ((qs[i] != '&') && (qs[i] != ';') && (i < len)) {
            /* replace '+' with ' ' */
            cpair[j] = (qs[i] == '+') ? ' ' : qs[i];
            i++;
            j++;
        }

        if (j) {
            /* PYTHON 2.5: '_PyString_Resize' uses Py_ssize_t for input parameters */ 
            _PyString_Resize(&pair, j);
            if (pair)
                PyList_Append(pairs, pair);
        }

        Py_XDECREF(pair);
        i++;
    }

    /*
     * now we have a list of "abc=def" string (pairs), let's split 
     * them all by '=' and put them in a dictionary.
     */
    
    dict = PyDict_New();
    if (dict == NULL)
        return NULL;

    /* PYTHON 2.5: 'PyList_Size' uses Py_ssize_t for input parameters */ 
    lsize = PyList_Size(pairs);
    n = 0;

    while (n < lsize) {

        PyObject *pair, *key, *val;
        char *cpair, *ckey, *cval;
        int k, v;

        pair = PyList_GET_ITEM(pairs, n);
        cpair = PyString_AS_STRING(pair);

        len = strlen(cpair);
        /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ 
        key = PyString_FromStringAndSize(NULL, len);
        if (key == NULL) 
            return NULL;
        /* PYTHON 2.5: 'PyString_FromStringAndSize' uses Py_ssize_t for input parameters */ 
        val = PyString_FromStringAndSize(NULL, len);
        if (val == NULL) 
            return NULL;

        ckey = PyString_AS_STRING(key);
        cval = PyString_AS_STRING(val);

        i = 0;
        k = 0;
        v = 0;
        while (i < len) {
            if (cpair[i] != '=') {
                ckey[k] = cpair[i];
                k++;
                i++;
            }
            else {
                i++;      /* skip '=' */
//.........这里部分代码省略.........
开发者ID:fabioz,项目名称:coev,代码行数:101,代码来源:cqsl.c


示例2: py_gauss_transform

static PyObject *
py_gauss_transform(PyObject *self, PyObject *args)
{
    int m,n,dim;
    double scale, result;
    double *grad;
    PyObject *A, *B;
    PyArrayObject *arrayA, *arrayB;
    PyArrayObject *arrayGrad;
    PyObject *list;

    /* send Python arrays to C */
    if (!PyArg_ParseTuple(args, "OOd",  &A, &B, &scale))
    {
        return NULL;
    }

    /* printf("getting input success. \n"); */
    arrayA = (PyArrayObject *) PyArray_ContiguousFromObject(A, PyArray_DOUBLE, 1, 2);
    arrayB = (PyArrayObject *) PyArray_ContiguousFromObject(B, PyArray_DOUBLE, 1, 2);

    /* printf("converting success!\n"); */

    if (arrayA->nd > 2 || arrayA->descr->type_num != PyArray_DOUBLE) {
        PyErr_SetString(PyExc_ValueError,
        "array must be two-dimensional and of type float");
        return NULL;
    }
    /* printf("checking input success!\n"); */

    m = (arrayA->dimensions)[0];
    n = (arrayB->dimensions)[0];
    if (arrayA->nd>1)
        dim = (arrayA->dimensions)[1];
    else
        dim = 1;
    /* printf("m=%d,n=%d,dim=%d\n",m,n,dim); */
    grad = (double *) malloc(m*dim*sizeof(double));

    /* call function */
    result = GaussTransform((double*)(arrayA->data), (double*)(arrayB->data), m, n, dim, scale, grad);

    /* PyArray_FromDimsAndData() deprecated, use PyArray_SimpleNewFromData()
    http://blog.enthought.com/?p=62
    arrayGrad = (PyArrayObject*) PyArray_FromDimsAndData(2,arrayA->dimensions,PyArray_DOUBLE, (char*)grad);
    */
    arrayGrad = PyArray_SimpleNewFromData(2,arrayA->dimensions,NPY_DOUBLE,grad);
    if (arrayGrad == NULL){
        printf("creating %dx%d array failed\n", arrayA->dimensions[0],arrayA->dimensions[1]);
        return NULL;
    }
    /* free(grad); */

    /* send the result back to Python */
    Py_DECREF(arrayA);
    Py_DECREF(arrayB);


    //Build a list; send it back to interpreter
    list = PyList_New(0);
    // Check the API documentation for meaning of
    // return values.
    if(PyList_Append(list, PyFloat_FromDouble(result)) != 0)
    {
     // set exception context, raise (return 0)
        return 0;
    }
    if(PyList_Append(list, PyArray_Return(arrayGrad)) != 0)
    {
     // set exception context, raise (return 0)
        return 0;
    }

    return list;
    //return PyArray_Return(arrayGrad);
    //return PyFloat_FromDouble(result);

    /*return Py_BuildValue("d", result);*/
}
开发者ID:alxio,项目名称:gmmreg,代码行数:79,代码来源:py_extension.c


示例3: host_cb

static void
host_cb(void *arg, int status, int timeouts, struct hostent *hostent)
{
    PyGILState_STATE gstate = PyGILState_Ensure();
    char ip[INET6_ADDRSTRLEN];
    char **ptr;
    ares_cb_data_t *data;
    DNSResolver *self;
    PyObject *callback, *dns_name, *errorno, *dns_aliases, *dns_addrlist, *dns_result, *tmp, *result;

    ASSERT(arg);

    data = (ares_cb_data_t*)arg;
    self = data->resolver;
    callback = data->cb;

    ASSERT(self);
    /* Object could go out of scope in the callback, increase refcount to avoid it */
    Py_INCREF(self);

    if (status != ARES_SUCCESS) {
        errorno = PyInt_FromLong((long)status);
        dns_result = Py_None;
        Py_INCREF(Py_None);
        goto callback;
    }

    dns_aliases = PyList_New(0);
    dns_addrlist = PyList_New(0);
    dns_result = PyTuple_New(3);

    if (!(dns_aliases && dns_addrlist && dns_result)) {
        PyErr_NoMemory();
        PyErr_WriteUnraisable(Py_None);
        Py_XDECREF(dns_aliases);
        Py_XDECREF(dns_addrlist);
        Py_XDECREF(dns_result);
        errorno = PyInt_FromLong((long)ARES_ENOMEM);
        dns_result = Py_None;
        Py_INCREF(Py_None);
        goto callback;
    }

    for (ptr = hostent->h_aliases; *ptr != NULL; ptr++) {
        if (*ptr != hostent->h_name && strcmp(*ptr, hostent->h_name)) {
            tmp = PyString_FromString(*ptr);
            if (tmp == NULL) {
                break;
            }
            PyList_Append(dns_aliases, tmp);
            Py_DECREF(tmp);
        }
    }
    for (ptr = hostent->h_addr_list; *ptr != NULL; ptr++) {
        if (hostent->h_addrtype == AF_INET) {
            uv_inet_ntop(AF_INET, *ptr, ip, INET_ADDRSTRLEN);
            tmp = PyString_FromString(ip);
        } else if (hostent->h_addrtype == AF_INET6) {
            uv_inet_ntop(AF_INET6, *ptr, ip, INET6_ADDRSTRLEN);
            tmp = PyString_FromString(ip);
        } else {
            continue;
        }
        if (tmp == NULL) {
            break;
        }
        PyList_Append(dns_addrlist, tmp);
        Py_DECREF(tmp);
    }
    dns_name = PyString_FromString(hostent->h_name);

    PyTuple_SET_ITEM(dns_result, 0, dns_name);
    PyTuple_SET_ITEM(dns_result, 1, dns_aliases);
    PyTuple_SET_ITEM(dns_result, 2, dns_addrlist);
    errorno = Py_None;
    Py_INCREF(Py_None);

callback:
    result = PyObject_CallFunctionObjArgs(callback, self, dns_result, errorno, NULL);
    if (result == NULL) {
        PyErr_WriteUnraisable(callback);
    }
    Py_XDECREF(result);

    Py_DECREF(callback);
    PyMem_Free(data);

    Py_DECREF(self);
    PyGILState_Release(gstate);
}
开发者ID:ikeikeikeike,项目名称:pyuv,代码行数:90,代码来源:dns.c


示例4: xcsoar_Airspaces_findIntrusions

PyObject* xcsoar_Airspaces_findIntrusions(Pyxcsoar_Airspaces *self, PyObject *args) {
  PyObject *py_flight = nullptr;

  if (!PyArg_ParseTuple(args, "O", &py_flight)) {
    PyErr_SetString(PyExc_AttributeError, "Can't parse argument.");
    return nullptr;
  }

  DebugReplay *replay = ((Pyxcsoar_Flight*)py_flight)->flight->Replay();

  if (replay == nullptr) {
    PyErr_SetString(PyExc_IOError, "Can't start replay - file not found.");
    return nullptr;
  }

  PyObject *py_result = PyDict_New();
  Airspaces::AirspaceVector last_airspaces;

  while (replay->Next()) {
    const MoreData &basic = replay->Basic();

    if (!basic.time_available || !basic.location_available ||
        !basic.NavAltitudeAvailable())
      continue;

    const auto range =
      self->airspace_database->QueryInside(ToAircraftState(basic,
                                                           replay->Calculated()));
    Airspaces::AirspaceVector airspaces(range.begin(), range.end());
    for (auto it = airspaces.begin(); it != airspaces.end(); it++) {
      PyObject *py_name = PyString_FromString((*it).GetAirspace().GetName());
      PyObject *py_airspace = nullptr,
               *py_period = nullptr;

      if (PyDict_Contains(py_result, py_name) == 0) {
        // this is the first fix inside this airspace
        py_airspace = PyList_New(0);
        PyDict_SetItem(py_result, py_name, py_airspace);

        py_period = PyList_New(0);
        PyList_Append(py_airspace, py_period);
        Py_DECREF(py_period);

      } else {
        // this airspace was hit some time before...
        py_airspace = PyDict_GetItem(py_result, py_name);

        // check if the last fix was already inside this airspace
        auto in_last = std::find(last_airspaces.begin(), last_airspaces.end(), *it);

        if (in_last == last_airspaces.end()) {
          // create a new period
          py_period = PyList_New(0);
          PyList_Append(py_airspace, py_period);
          Py_DECREF(py_period);
        } else {
          py_period = PyList_GET_ITEM(py_airspace, PyList_GET_SIZE(py_airspace) - 1);
        }
      }

      PyList_Append(py_period, Py_BuildValue("{s:N,s:N}",
        "time", Python::BrokenDateTimeToPy(basic.date_time_utc),
        "location", Python::WriteLonLat(basic.location)));
    }

    last_airspaces = std::move(airspaces);
  }

  delete replay;

  return py_result;
}
开发者ID:Advi42,项目名称:XCSoar,代码行数:72,代码来源:Airspaces.cpp


示例5: archpy_disassemble

static PyObject *
archpy_disassemble (PyObject *self, PyObject *args, PyObject *kw)
{
  static char *keywords[] = { "start_pc", "end_pc", "count", NULL };
  CORE_ADDR start, end = 0;
  CORE_ADDR pc;
  gdb_py_ulongest start_temp;
  long count = 0, i;
  PyObject *result_list, *end_obj = NULL, *count_obj = NULL;
  struct gdbarch *gdbarch = NULL;

  ARCHPY_REQUIRE_VALID (self, gdbarch);

  if (!PyArg_ParseTupleAndKeywords (args, kw, GDB_PY_LLU_ARG "|OO", keywords,
                                    &start_temp, &end_obj, &count_obj))
    return NULL;

  start = start_temp;
  if (end_obj)
    {
      /* Make a long logic check first.  In Python 3.x, internally,
	 all integers are represented as longs.  In Python 2.x, there
	 is still a differentiation internally between a PyInt and a
	 PyLong.  Explicitly do this long check conversion first. In
	 GDB, for Python 3.x, we #ifdef PyInt = PyLong.  This check has
	 to be done first to ensure we do not lose information in the
	 conversion process.  */
      if (PyLong_Check (end_obj))
        end = PyLong_AsUnsignedLongLong (end_obj);
      else if (PyInt_Check (end_obj))
        /* If the end_pc value is specified without a trailing 'L', end_obj will
           be an integer and not a long integer.  */
        end = PyInt_AsLong (end_obj);
      else
        {
          Py_DECREF (end_obj);
          Py_XDECREF (count_obj);
          PyErr_SetString (PyExc_TypeError,
                           _("Argument 'end_pc' should be a (long) integer."));

          return NULL;
        }

      if (end < start)
        {
          Py_DECREF (end_obj);
          Py_XDECREF (count_obj);
          PyErr_SetString (PyExc_ValueError,
                           _("Argument 'end_pc' should be greater than or "
                             "equal to the argument 'start_pc'."));

          return NULL;
        }
    }
  if (count_obj)
    {
      count = PyInt_AsLong (count_obj);
      if (PyErr_Occurred () || count < 0)
        {
          Py_DECREF (count_obj);
          Py_XDECREF (end_obj);
          PyErr_SetString (PyExc_TypeError,
                           _("Argument 'count' should be an non-negative "
                             "integer."));

          return NULL;
        }
    }

  result_list = PyList_New (0);
  if (result_list == NULL)
    return NULL;

  for (pc = start, i = 0;
       /* All args are specified.  */
       (end_obj && count_obj && pc <= end && i < count)
       /* end_pc is specified, but no count.  */
       || (end_obj && count_obj == NULL && pc <= end)
       /* end_pc is not specified, but a count is.  */
       || (end_obj == NULL && count_obj && i < count)
       /* Both end_pc and count are not specified.  */
       || (end_obj == NULL && count_obj == NULL && pc == start);)
    {
      int insn_len = 0;
      char *as = NULL;
      struct ui_file *memfile = mem_fileopen ();
      PyObject *insn_dict = PyDict_New ();

      if (insn_dict == NULL)
        {
          Py_DECREF (result_list);
          ui_file_delete (memfile);

          return NULL;
        }
      if (PyList_Append (result_list, insn_dict))
        {
          Py_DECREF (result_list);
          Py_DECREF (insn_dict);
          ui_file_delete (memfile);
//.........这里部分代码省略.........
开发者ID:ChrisG0x20,项目名称:gdb,代码行数:101,代码来源:py-arch.c


示例6: get_device_ancestors

PSP_DEVICE_INTERFACE_DETAIL_DATA
get_device_ancestors(HDEVINFO hDevInfo, DWORD index, PyObject *candidates, BOOL *iterate, BOOL ddebug) {
    SP_DEVICE_INTERFACE_DATA            interfaceData;
    SP_DEVINFO_DATA						devInfoData;
    BOOL                                status;
    PSP_DEVICE_INTERFACE_DETAIL_DATA    interfaceDetailData;
    DWORD                               interfaceDetailDataSize,
                                        reqSize;
    DEVINST                             parent, pos;
    wchar_t                             temp[BUFSIZE];
    int                                 i;
    PyObject                            *devid;

    interfaceData.cbSize = sizeof (SP_INTERFACE_DEVICE_DATA);
    devInfoData.cbSize   = sizeof (SP_DEVINFO_DATA);

    status = SetupDiEnumDeviceInterfaces (
                hDevInfo,               // Interface Device Info handle
                NULL,                   // Device Info data
                (LPGUID)&GUID_DEVINTERFACE_VOLUME, // Interface registered by driver
                index,                  // Member
                &interfaceData          // Device Interface Data
                );
    if ( status == FALSE ) {
        *iterate = FALSE;
        return NULL;
    }
    SetupDiGetDeviceInterfaceDetail (
                hDevInfo,           // Interface Device info handle
                &interfaceData,     // Interface data for the event class
                NULL,               // Checking for buffer size
                0,                  // Checking for buffer size
                &reqSize,           // Buffer size required to get the detail data
                NULL                // Checking for buffer size
    );

    interfaceDetailDataSize = reqSize;
    interfaceDetailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)PyMem_Malloc(interfaceDetailDataSize+50);
    if ( interfaceDetailData == NULL ) {
        PyErr_NoMemory();
        return NULL;
    }
    interfaceDetailData->cbSize = sizeof (SP_INTERFACE_DEVICE_DETAIL_DATA);
    devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);

    status = SetupDiGetDeviceInterfaceDetail (
                  hDevInfo,                 // Interface Device info handle
                  &interfaceData,           // Interface data for the event class
                  interfaceDetailData,      // Interface detail data
                  interfaceDetailDataSize,  // Interface detail data size
                  &reqSize,                 // Buffer size required to get the detail data
                  &devInfoData);            // Interface device info
    if (ddebug) printf("Getting ancestors\n"); fflush(stdout);

    if ( status == FALSE ) {PyErr_SetFromWindowsErr(0); PyMem_Free(interfaceDetailData); return NULL;}

    pos = devInfoData.DevInst;

    for(i = 0; i < 10; i++) {
        // Get the device instance of parent.
        if (CM_Get_Parent(&parent, pos, 0) != CR_SUCCESS) break;
        if (CM_Get_Device_ID(parent, temp, BUFSIZE, 0) == CR_SUCCESS) {
            if (ddebug) console_out(L"device id: %s\n", temp);
            devid = PyUnicode_FromWideChar(temp, wcslen(temp));
            if (devid) {
                PyList_Append(candidates, devid);
                Py_DECREF(devid);
            }
        }
        pos = parent;
    }

    return interfaceDetailData;
}
开发者ID:yeyanchao,项目名称:calibre,代码行数:74,代码来源:winutil.c


示例7: Printer_init

static int Printer_init(Printer *self, PyObject * /*args*/, PyObject * /*kwds*/)
{
	if (!checkHaveDocument()) {
		return -1;
	}
// pool system for installed printers
// most code is stolen and little adopted from druck.cpp
	PyObject *allPrinters = PyList_New(0);
	if (allPrinters){
		Py_DECREF(self->allPrinters);
		self->allPrinters = allPrinters;
	}
	QStringList printers = PrinterUtil::getPrinterNames();
	for (int i = 0; i < printers.count(); ++i)
	{
		QString prn = printers[i];
		if (prn.isEmpty())
			continue;
		PyObject *tmppr = PyString_FromString(prn.toLocal8Bit().constData());
		if (tmppr){
			PyList_Append(self->allPrinters, tmppr);
			Py_DECREF(tmppr);
		}
	}
	PyObject *tmp2 = PyString_FromString("File");
	PyList_Append(self->allPrinters, tmp2);
	Py_DECREF(tmp2);
// as defaut set to print into file
	PyObject *printer = NULL;
	printer = PyString_FromString("File");
	if (printer){
		Py_DECREF(self->printer);
		self->printer = printer;
	}
// set defaul name of file to print into
	QString tf(ScCore->primaryMainWindow()->doc->pdfOptions().fileName);
	if (tf.isEmpty()) {
		QFileInfo fi = QFileInfo(ScCore->primaryMainWindow()->doc->DocName);
		tf = fi.path()+"/"+fi.baseName()+".pdf";
	}
	PyObject *file = NULL;
	file = PyString_FromString(tf.toLatin1());
	if (file){
		Py_DECREF(self->file);
		self->file = file;
	} else {
		PyErr_SetString(PyExc_SystemError, "Can not initialize 'file' attribute");
		return -1;
	}
// alternative printer commands default to ""
	PyObject *cmd = NULL;
	cmd = PyString_FromString("");
	if (cmd){
		Py_DECREF(self->cmd);
		self->cmd = cmd;
	}
// if document exist when created Printer instance
// set to print all pages
	PyObject *pages = NULL;
	int num = ScCore->primaryMainWindow()->doc->Pages->count();
	pages = PyList_New(num);
	if (pages){
		Py_DECREF(self->pages);
		self->pages = pages;
	}
	for (int i = 0; i<num; i++) {
		PyObject *tmp=NULL;
		tmp = PyInt_FromLong((long)i+1L); // instead of 1 put here first page number
		if (tmp)
			PyList_SetItem(self->pages, i, tmp);
	}
// do not print separation
	PyObject *separation = NULL;
	separation = PyString_FromString("No");
	if (separation){
		Py_DECREF(self->separation);
		self->separation = separation;
	}
// print in color
	self->color = 1;
// do not use ICC Profile
	self->useICC = 0;
// use PostScrip level 3
	self->pslevel = 3;
// do not mirror pages
	self->mph = 0;
// do not mirror pages
	self->mpv = 0;
// apply Under Color Removal as default
	self->ucr = 1;
// number of copies
	self->copies = 1;
	return 0;
}
开发者ID:HOST-Oman,项目名称:scribus,代码行数:94,代码来源:objprinter.cpp


示例8: parse_desc

/* Modified portion of _alpm_db_read from lib/libalpm/be_local.c */
int parse_desc(FILE *stream, PyObject **ppkg) {
	/* add to ppkg dict the values found in desc file */
	char line[1024];
	PyObject *s, *pyl, *pkg=*ppkg;

	while(!feof(stream)) {
		if(fgets(line, sizeof(line), stream) == NULL) {
			break;
		}
		strtrim(line);
		if(strcmp(line, "%NAME%") == 0) {
			if(fgets(line, sizeof(line), stream) == NULL) {
				goto error;
			}
			PyObject *tmp = PyDict_GetItemString(pkg, "name"); /* borrowed ref. ! */
			if (tmp != NULL) {
				const char *pkgname = PyString_AsString(tmp);
				if(strcmp(strtrim(line), pkgname) != 0) {
					/* we have a problem */
					return -1;
				}
			} else {
				s = PyString_FromString(strtrim(line));
				PyDict_SetItemString(pkg, "name", s);
				Py_DECREF(s);
			}
		} else if(strcmp(line, "%VERSION%") == 0) {
			if(fgets(line, sizeof(line), stream) == NULL) {
				goto error;
			}
			PyObject *tmp = PyDict_GetItemString(pkg, "version");
			if (tmp != NULL) {
				const char *pkgver = PyString_AsString(tmp);
				if(strcmp(strtrim(line), pkgver) != 0) {
					/* we have a problem */
					return -1;
				}
			} else {
				s = PyString_FromString(strtrim(line));
				PyDict_SetItemString(pkg, "version", s);
				Py_DECREF(s);
			}
		} else if(strcmp(line, "%FILENAME%") == 0) {
			if(fgets(line, sizeof(line), stream) == NULL) {
				goto error;
			}
			s = PyString_FromString(strtrim(line));
			PyDict_SetItemString(pkg, "filename", s);
			Py_DECREF(s);
		} else if(strcmp(line, "%DESC%") == 0) {
			if(fgets(line, sizeof(line), stream) == NULL) {
				goto error;
			}
			s = PyString_FromString(strtrim(line));
			PyDict_SetItemString(pkg, "desc", s);
			Py_DECREF(s);
		} else if(strcmp(line, "%GROUPS%") == 0) {
			PyObject *groups = PyList_New(0);
			while(fgets(line, sizeof(line), stream) && strlen(strtrim(line))) {
				s = PyString_FromString(strtrim(line));
				PyList_Append(groups, s);
				Py_DECREF(s);
			}
			PyDict_SetItemString(pkg, "groups", groups);
			Py_DECREF(groups);
		} else if(strcmp(line, "%URL%") == 0) {
			if(fgets(line, sizeof(line), stream) == NULL) {
				goto error;
			}
			s = PyString_FromString(strtrim(line));
			PyDict_SetItemString(pkg, "url", s);
			Py_DECREF(s);
		} else if(strcmp(line, "%LICENSE%") == 0) {
			PyObject *license = PyList_New(0);
			while(fgets(line, sizeof(line), stream) && strlen(strtrim(line))) {
				s = PyString_FromString(strtrim(line));
				PyList_Append(license, s);
				Py_DECREF(s);
			}
			PyDict_SetItemString(pkg, "license", license);
			Py_DECREF(license);
		} else if(strcmp(line, "%ARCH%") == 0) {
			if(fgets(line, sizeof(line), stream) == NULL) {
				goto error;
			}
			s = PyString_FromString(strtrim(line));
			PyDict_SetItemString(pkg, "arch", s);
			Py_DECREF(s);
		} else if(strcmp(line, "%BUILDDATE%") == 0) {
			if(fgets(line, sizeof(line), stream) == NULL) {
				goto error;
			}
			strtrim(line);

			char first = tolower((unsigned char)line[0]);
			long ltmp;
			if(first > 'a' && first < 'z') {
				struct tm tmp_tm = {0}; /* initialize to null in case of failure */
				setlocale(LC_TIME, "C");
//.........这里部分代码省略.........
开发者ID:mineo,项目名称:pkgtools,代码行数:101,代码来源:parse.c


示例9: PyErr_SetString


//.........这里部分代码省略.........
	archive_read_open_filename(a, filename, 10240);
	l = NULL;
	while (archive_read_next_header(a, &entry) == ARCHIVE_OK) {
		if(!S_ISREG(archive_entry_filetype(entry))) {
			archive_read_data_skip(a);
			continue;
		}
		strncpy(pname, archive_entry_pathname(entry), ABUFLEN-1);
		fname = basename(pname);
		dname = dirname(pname);
		if (splitname(dname, &p, &v) == -1) {
			archive_read_data_skip(a);
			continue;
		}
		found = 0;
		for (i=0; i<lp; i++) {
			pkgname = PyString_AsString(PyList_GetItem(pkgnames_list, i));
			if (pkgname == NULL) {
				goto error;
			}
			if (strcmp(p, pkgname) == 0) {
				found = 1;
				break;
			}
		}
		free(p);
		free(v);

		if (!found) {
			archive_read_data_skip(a);
			continue;
		}

		pkg = PyDict_GetItemString(waiting_dict, pkgname);
		existing = 1;
		if (pkg == NULL) {
			existing = 0;
			pkg = PyDict_New();
			if (pkg == NULL) {
				goto error;
			}
		}

		if(strcmp(fname, "desc") == 0) {
			stream = open_archive_stream(a);
			if (!stream) {
				PyErr_SetString(PyExc_IOError, "Unable to open archive stream.");
				goto error;
			}

			if (parse_desc(stream, &pkg) == -1) {
				fclose(stream);
				if (!existing) Py_DECREF(pkg);
				continue;
			}
			fclose(stream);
		} else if (strcmp(fname, "depends") == 0) {
			stream = open_archive_stream(a);
			if (!stream) {
				PyErr_SetString(PyExc_IOError, "Unable to open archive stream.");
				goto error;
			}

			if (parse_depends(stream, &pkg) == -1) {
				fclose(stream);
				if (!existing) Py_DECREF(pkg);
				continue;
			}
			fclose(stream);
		} else {
			archive_read_data_skip(a);
			continue;
		}

		if (existing) {
			PyList_Append(ret, pkg);
			PyDict_DelItemString(waiting_dict, pkgname);
			pkg = NULL;
		} else {
			PyDict_SetItemString(waiting_dict, pkgname, pkg);
			Py_DECREF(pkg);
		}
	}
	if(l)
		free(l);

	archive_read_finish(a);

	/* we discard element still present in waiting_dict because they miss either the desc
	 * or depends values */
	Py_DECREF(waiting_dict);

	return ret;

error:
	Py_XDECREF(ret);
	Py_XDECREF(waiting_dict);
	Py_XDECREF(pkg);
	return NULL;
}
开发者ID:mineo,项目名称:pkgtools,代码行数:101,代码来源:parse.c


示例10: binop


//.........这里部分代码省略.........
            break;
        case BINARY_AND:
            newconst = PyNumber_And(v, w);
            break;
        case BINARY_XOR:
            newconst = PyNumber_Xor(v, w);
            break;
        case BINARY_OR:
            newconst = PyNumber_Or(v, w);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected binary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
            PyErr_Clear();
        return 0;
    }
    size = PyObject_Size(newconst);
    if (size == -1) {
        if (PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
            return 0;
        PyErr_Clear();
    } else if (size > 20) {
        Py_DECREF(newconst);
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP NOP NOP NOP LOAD_CONST newconst */
    memset(codestr, NOP, 4);
    codestr[4] = LOAD_CONST;
    SETARG(codestr, 4, len_consts);
    return 1;
}

static int
fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
{
    PyObject *newconst=NULL, *v;
    Py_ssize_t len_consts;
    int opcode;

    /* Pre-conditions */
    assert(PyList_CheckExact(consts));
    assert(codestr[0] == LOAD_CONST);

    /* Create new constant */
    v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
    opcode = codestr[3];
    switch (opcode) {
        case UNARY_NEGATIVE:
            /* Preserve the sign of -0.0 */
            if (PyObject_IsTrue(v) == 1)
                newconst = PyNumber_Negative(v);
            break;
        case UNARY_INVERT:
            newconst = PyNumber_Invert(v);
            break;
        case UNARY_POSITIVE:
            newconst = PyNumber_Positive(v);
            break;
        default:
            /* Called with an unknown opcode */
            PyErr_Format(PyExc_SystemError,
                 "unexpected unary operation %d on a constant",
                     opcode);
            return 0;
    }
    if (newconst == NULL) {
        if(!PyErr_ExceptionMatches(PyExc_KeyboardInterrupt))
            PyErr_Clear();
        return 0;
    }

    /* Append folded constant into consts table */
    len_consts = PyList_GET_SIZE(consts);
    if (PyList_Append(consts, newconst)) {
        Py_DECREF(newconst);
        return 0;
    }
    Py_DECREF(newconst);

    /* Write NOP LOAD_CONST newconst */
    codestr[0] = NOP;
    codestr[1] = LOAD_CONST;
    SETARG(codestr, 1, len_consts);
    return 1;
}
开发者ID:AndyPanda95,项目名称:python-for-android,代码行数:101,代码来源:peephole.c


示例11: PyList_New

static PyObject *py_parse_tree(PyObject *self, PyObject *args)
{
	char *text, *start, *end;
	int len, namelen;
	PyObject *ret, *item, *name;

	if (!PyArg_ParseTuple(args, "s#", &text, &len))
		return NULL;

	/* TODO: currently this returns a list; if memory usage is a concern,
	* consider rewriting as a custom iterator object */
	ret = PyList_New(0);

	if (ret == NULL) {
		return NULL;
	}

	start = text;
	end = text + len;

	while (text < end) {
		long mode;
		mode = strtol(text, &text, 8);

		if (*text != ' ') {
			PyErr_SetString(PyExc_ValueError, "Expected space");
			Py_DECREF(ret);
			return NULL;
		}

		text++;

		namelen = strnlen(text, len - (text - start));

		name = PyString_FromStringAndSize(text, namelen);
		if (name == NULL) {
			Py_DECREF(ret);
			return NULL;
		}

		if (text + namelen + 20 >= end) {
			PyErr_SetString(PyExc_ValueError, "SHA truncated");
			Py_DECREF(ret);
			Py_DECREF(name);
			return NULL;
		}

		item = Py_BuildValue("(NlN)", name, mode,
							 sha_to_pyhex((unsigned char *)text+namelen+1));
		if (item == NULL) {
			Py_DECREF(ret);
			Py_DECREF(name);
			return NULL;
		}
		if (PyList_Append(ret, item) == -1) {
			Py_DECREF(ret);
			Py_DECREF(item);
			return NULL;
		}
		Py_DECREF(item);

		text += namelen+21;
	}

	return ret;
}
开发者ID:dmgctrl,项目名称:dulwich,代码行数:66,代码来源:_objects.c


示例12: psutil_net_if_addrs

/*
 * Return NICs information a-la ifconfig as a list of tuples.
 * TODO: on Solaris we won't get any MAC address.
 */
static PyObject*
psutil_net_if_addrs(PyObject* self, PyObject* args) {
    struct ifaddrs *ifaddr, *ifa;
    int family;

    PyObject *py_retlist = PyList_New(0);
    PyObject *py_tuple = NULL;
    PyObject *py_address = NULL;
    PyObject *py_netmask = NULL;
    PyObject *py_broadcast = NULL;
    PyObject *py_ptp = NULL;

    if (py_retlist == NULL)
        return NULL;
    if (getifaddrs(&ifaddr) == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
        if (!ifa->ifa_addr)
            continue;
        family = ifa->ifa_addr->sa_family;
        py_address = psutil_convert_ipaddr(ifa->ifa_addr, family);
        // If the primary address can't be determined just skip it.
        // I've never seen this happen on Linux but I did on FreeBSD.
        if (py_address == Py_None)
            continue;
        if (py_address == NULL)
            goto error;
        py_netmask = psutil_convert_ipaddr(ifa->ifa_netmask, family);
        if (py_netmask == NULL)
            goto error;

        if (ifa->ifa_flags & IFF_BROADCAST) {
            py_broadcast = psutil_convert_ipaddr(ifa->ifa_broadaddr, family);
            Py_INCREF(Py_None);
            py_ptp = Py_None;
        }
        else if (ifa->ifa_flags & IFF_POINTOPOINT) {
            py_ptp = psutil_convert_ipaddr(ifa->ifa_dstaddr, family);
            Py_INCREF(Py_None);
            py_broadcast = Py_None;
        }
        else {
            Py_INCREF(Py_None);
            Py_INCREF(Py_None);
            py_broadcast = Py_None;
            py_ptp = Py_None;
        }

        if ((py_broadcast == NULL) || (py_ptp == NULL))
            goto error;
        py_tuple = Py_BuildValue(
            "(siOOOO)",
            ifa->ifa_name,
            family,
            py_address,
            py_netmask,
            py_broadcast,
            py_ptp
        );

        if (! py_tuple)
            goto error;
        if (PyList_Append(py_retlist, py_tuple))
            goto error;
        Py_DECREF(py_tuple);
        Py_DECREF(py_address);
        Py_DECREF(py_netmask);
        Py_DECREF(py_broadcast);
        Py_DECREF(py_ptp);
    }

    freeifaddrs(ifaddr);
    return py_retlist;

error:
    if (ifaddr != NULL)
        freeifaddrs(ifaddr);
    Py_DECREF(py_retlist);
    Py_XDECREF(py_tuple);
    Py_XDECREF(py_address);
    Py_XDECREF(py_netmask);
    Py_XDECREF(py_broadcast);
    Py_XDECREF(py_ptp);
    return NULL;
}
开发者ID:giampaolo,项目名称:psutil,代码行数:92,代码来源:_psutil_posix.c


示例13: distorm_Decode

PyObject* distorm_Decode(PyObject* pSelf, PyObject* pArgs)
{
	_DecodeType dt;
	uint8_t* code;
	int codeLen;
	_OffsetType codeOffset;
	_DecodeResult res = DECRES_NONE;

	_DecodedInst decodedInstructions[MAX_INSTRUCTIONS];
	unsigned int decodedInstructionsCount = 0, i = 0, next = 0;

	uint8_t instructionText[MAX_TEXT_SIZE*2];


	PyObject *ret = NULL, *pyObj = NULL, *dtObj = NULL;

	pSelf = pSelf; /* UNREFERENCED_PARAMETER */

	/* Decode(int32/64 offset, string code, int type=Decode32Bits) */
	if (!PyArg_ParseTuple(pArgs, _PY_OFF_INT_SIZE_ "s#|O", &codeOffset, &code, &codeLen, &dtObj)) return NULL;

	if (code == NULL) {
		PyErr_SetString(PyExc_IOError, "Error while reading code buffer.");
		return NULL;
	}

	if (codeLen < 0) {
		PyErr_SetString(PyExc_OverflowError, "Code buffer is too long.");
		return NULL;
	}

	/* Default parameter. */
	if (dtObj == NULL) dt = Decode32Bits;
	else if (!PyInt_Check(dtObj)) {
		PyErr_SetString(PyExc_IndexError, "Third parameter must be either Decode16Bits, Decode32Bits or Decode64Bits (integer type).");
		return NULL;
	} else dt = (_DecodeType)PyInt_AsUnsignedLongMask(dtObj);

	if ((dt != Decode16Bits) && (dt != Decode32Bits) && (dt != Decode64Bits)) {
		PyErr_SetString(PyExc_IndexError, "Decoding-type must be either Decode16Bits, Decode32Bits or Decode64Bits.");
		return NULL;
	}

	/* Construct an empty list, which later will be filled with tuples of (offset, size, mnemonic, hex). */
	ret = PyList_New(0);
	if (ret == NULL) {
		PyErr_SetString(PyExc_MemoryError, "Not enough memory to initialize a list.");
		return NULL;
	}

	while (res != DECRES_SUCCESS) {
		res = internal_decode(codeOffset, code, codeLen, dt, decodedInstructions, MAX_INSTRUCTIONS, &decodedInstructionsCount);

		if ((res == DECRES_MEMORYERR) && (decodedInstructionsCount == 0)) break;

		for (i = 0; i < decodedInstructionsCount; i++) {
			if (decodedInstructions[i].mnemonic.pos > 0) {
				memcpy(instructionText, decodedInstructions[i].mnemonic.p, decodedInstructions[i].mnemonic.pos + 1); /* Include \0. */
				if (decodedInstructions[i].operands.pos > 0)
					instructionText[decodedInstructions[i].mnemonic.pos] = SP_CHR;
				memcpy(&instructionText[decodedInstructions[i].mnemonic.pos+1], decodedInstructions[i].operands.p, decodedInstructions[i].operands.pos + 1);
			} else instructionText[0] = '\0';

			pyObj = Py_BuildValue("(" _PY_OFF_INT_SIZE_ "bss)", decodedInstructions[i].offset, decodedInstructions[i].size, instructionText, decodedInstructions[i].instructionHex.p);
			if (pyObj == NULL) {
				Py_DECREF(ret);
				PyErr_SetString(PyExc_MemoryError, "Not enough memory to append an item into the list.");
				return NULL;
			}
			if (PyList_Append(ret, pyObj) == -1) {
				Py_DECREF(pyObj);
				Py_DECREF(ret);
				PyErr_SetString(PyExc_MemoryError, "Not enough memory to append an item into the list.");
				return NULL;
			}
			// V 1.7.25 - Memleak fixed, it is necessary to DECREF the object, because PyList_Append INCREFs it on its own.
			Py_DECREF(pyObj);
		}

		/* Get offset difference. */
		next = (unsigned int)(decodedInstructions[decodedInstructionsCount-1].offset - codeOffset);
		next += decodedInstructions[decodedInstructionsCount-1].size;

		/* Advance ptr and recalc offset. */
		code += next;
		codeLen -= next;
		codeOffset += next;
	}

	return ret;
}
开发者ID:anarchivist,项目名称:pyflag,代码行数:91,代码来源:pydistorm.c


示例14: psutil_proc_memory_maps


//.........这里部分代码省略.........
    if (stat(path, &st) == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    size = st.st_size;

    fd = open(path, O_RDONLY);
    if (fd == -1) {
        PyErr_SetFromErrno(PyExc_OSError);
        goto error;
    }

    xmap = (prxmap_t *)malloc(size);
    if (xmap == NULL) {
        PyErr_NoMemory();
        goto error;
    }

    nread = pread(fd, xmap, size, 0);
    nmap = nread / sizeof(prxmap_t);
    p = xmap;

    while (nmap) {
        nmap -= 1;
        if (p == NULL) {
            p += 1;
            continue;
        }

        perms[0] = '\0';
        pr_addr_sz = p->pr_vaddr + p->pr_size;

        // perms
        sprintf(perms, "%c%c%c%c%c%c", p->pr_mflags & MA_READ ? 'r' : '-',
                p->pr_mflags & MA_WRITE ? 'w' : '-',
                p->pr_mflags & MA_EXEC ? 'x' : '-',
                p->pr_mflags & MA_SHARED ? 's' : '-',
                p->pr_mflags & MA_NORESERVE ? 'R' : '-',
                p->pr_mflags & MA_RESERVED1 ? '*' : ' ');

        // name
        if (strlen(p->pr_mapname) > 0) {
            name = p->pr_mapname;
        }
        else {
            if ((p->pr_mflags & MA_ISM) || (p->pr_mflags & MA_SHM)) {
                name = "[shmid]";
            }
            else {
                stk_base_sz = status.pr_stkbase + status.pr_stksize;
                brk_base_sz = status.pr_brkbase + status.pr_brksize;

                if ((pr_addr_sz > status.pr_stkbase) &&
                        (p->pr_vaddr < stk_base_sz)) {
                    name = "[stack]";
                }
                else if ((p->pr_mflags & MA_ANON) && \
                         (pr_addr_sz > status.pr_brkbase) && \
                         (p->pr_vaddr < brk_base_sz)) {
                    name = "[heap]";
                }
                else {
                    name = "[anon]";
                }
            }
        }

        py_tuple = Py_BuildValue(
            "iisslll",
            p->pr_vaddr,
            pr_addr_sz,
            perms,
            name,
            (long)p->pr_rss * p->pr_pagesize,
            (long)p->pr_anon * p->pr_pagesize,
            (long)p->pr_locked * p->pr_pagesize);
        if (!py_tuple)
            goto error;
        if (PyList_Append(py_retlist, py_tuple))
            goto error;
        Py_DECREF(py_tuple);

        // increment pointer
        p += 1;
    }

    close(fd);
    free(xmap);
    return py_retlist;

error:
    if (fd != -1)
        close(fd);
    Py_XDECREF(py_tuple);
    Py_DECREF(py_retlist);
    if (xmap != NULL)
        free(xmap);
    return NULL;
}
开发者ID:Alren-huang,项目名称:psutil,代码行数:101,代码来源:_psutil_sunos.c


示例15: PYEXPR_ERROR

void
avtPythonExpression::ProcessArguments(ArgsExpr *args,
                                      ExprPipelineState *state)
{

    // get the argument list and # of arguments
    std::vector<ArgExpr*> *arguments = args->GetArgs();
    int nargs = arguments->size();

    // check for call with improper # of arguments
    if (nargs < 2)
        PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - "
                     "Python Filter Expression requires at least to input "
                     "arguments:\n"
                     "A variable and a string providing the python filter "
                     "source");

    // the last argument should be the python script defining the filter.
    // attempt to load it first:
    pyScript = "";

    ExprParseTreeNode *last_node =  ((*arguments)[nargs-1])->GetExpr();
    std::string last_node_type = last_node ->GetTypeName();


    if(last_node_type != "StringConst")
        PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - "
                     "Last expression argument must be a string constant"
                     "containing a python filter source.");

    pyScript = dynamic_cast<StringConstExpr*>(last_node)->GetValue();
    if(!pyEnv->Initialize())
        PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - "
                     "Failed to initialize the python filter environment.");

    if(!pyEnv->LoadFilter(pyScript))
        PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - "
                     "Failed to load python filter script.");

    PyObject *py_vars_list = pyEnv->Filter()->FetchAttribute("input_var_names");
    if(py_vars_list == NULL || !PyList_Check(py_vars_list))
        PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - "
                     "Failed to fetch 'input_var_names' "
                     "list from python filter");

    PyObject *py_args_list = pyEnv->Filter()->FetchAttribute("arguments");
    if(py_args_list == NULL || !PyList_Check(py_args_list))
        PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - "
                     "Failed to fetch 'arguments' list "
                     "from python filter.");

    // process the remaining arguments
    for(int i=0;i< nargs-1;i++)
    {
        ExprParseTreeNode *node =  ((*arguments)[i])->GetExpr();
        std::string node_type = node->GetTypeName();
        PyObject *py_arg = NULL;

        if(node_type == "IntegerConst")
        {
            long ival = (long)dynamic_cast<IntegerConstExpr*>(node)->GetValue();
            // create PyInt
            py_arg = PyInt_FromLong(ival);
        }
        else if(node_type == "FloatConst")
        {
            double fval = dynamic_cast<FloatConstExpr*>(node)->GetValue();
            // create PyFloat
            py_arg = PyFloat_FromDouble(fval);
        }
        else if(node_type == "StringConst")
        {
            std::string sval = dynamic_cast<StringConstExpr*>(node)->GetValue();
            // create Py_STRING
            py_arg = PyString_FromString(sval.c_str());
        }
        else if(node_type == "BooleanConst")
        {
            bool bval = dynamic_cast<BooleanConstExpr*>(node)->GetValue();
            // select either Py_True or Py_False
            if(bval)
               py_arg = Py_True;
            else
               py_arg = Py_False;

            Py_INCREF(py_arg);
        }


        if(py_arg)
        {
            // if it is a constant add it to the filter's arguments list
            // append to the filter's arguments list
            if(PyList_Append(py_args_list,py_arg) == -1)
                PYEXPR_ERROR("avtPythonExpression::ProcessArguments Error - "
                     "Unable to add argument value to Python filter "
                     "'arguments' list.");

        }
        else
//.........这里部分代码省略.........
开发者ID:HarinarayanKrishnan,项目名称:VisIt26RC_Trunk,代码行数:101,代码来源:avtPythonExpression.C


示例16: psutil_net_connections


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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