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

C++ PyObject_IsTrue函数代码示例

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

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



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

示例1: arrayflags_writebackifcopy_set

/* relies on setflags order being write, align, uic */
static int
arrayflags_writebackifcopy_set(PyArrayFlagsObject *self, PyObject *obj)
{
    PyObject *res;

    if (obj == NULL) {
        PyErr_SetString(PyExc_AttributeError,
                "Cannot delete flags writebackifcopy attribute");
        return -1;
    }
    if (self->arr == NULL) {
        PyErr_SetString(PyExc_ValueError,
                "Cannot set flags on array scalars.");
        return -1;
    }
    res = PyObject_CallMethod(self->arr, "setflags", "OOO", Py_None, Py_None,
                              (PyObject_IsTrue(obj) ? Py_True : Py_False));
    if (res == NULL) {
        return -1;
    }
    Py_DECREF(res);
    return 0;
}
开发者ID:chinaloryu,项目名称:numpy,代码行数:24,代码来源:flagsobject.c


示例2: handle_boolean

static PyObject *
handle_boolean(lcb_t instance,
               int cmd, int mode, PyObject *val, lcb_error_t *err)
{
    int cval;
    PyObject *ret;

    if (val != NULL) {
        cval = PyObject_IsTrue(val);
    }

    if ( (*err = lcb_cntl(instance, mode, cmd, &cval)) != LCB_SUCCESS) {
        return NULL;
    }

    if (cval) {
        ret = Py_True;
    } else {
        ret = Py_False;
    }
    Py_INCREF(ret);
    return ret;
}
开发者ID:hahla,项目名称:couchbase-python-client,代码行数:23,代码来源:cntl.c


示例3: load

static PyObject *
load(XLPyBook *self, PyObject *args)
{
	const char* fileName;
	int size;
	PyObject *raw = NULL;
	if(!PyArg_ParseTuple(args, "s#|O!", &fileName, &size, &PyBool_Type, &raw))
		return NULL;

	if (raw && PyObject_IsTrue(raw)) {
		// fileName is treated as the buffer
		if(!xlBookLoadRaw(self->handler, fileName, size)) {
			Py_RETURN_FALSE;
		}
	}
	else {
		if(!xlBookLoad(self->handler, fileName)) {
			Py_RETURN_FALSE;
		}
	}

	Py_RETURN_TRUE;
}
开发者ID:nahody,项目名称:libxlpy,代码行数:23,代码来源:book.c


示例4: py2scm_exception

static void py2scm_exception(void)
{
	PyObject *ptype = NULL, *pvalue = NULL, *ptraceback = NULL;
	PyErr_Fetch(&ptype, &pvalue, &ptraceback);

	PyObject *pvalue_str = NULL;
	if (pvalue) {
		pvalue_str = PyObject_Str(pvalue);
		if (pvalue_str == NULL)
			PyErr_Clear();
	}

	scm_throw(scm_from_utf8_symbol("python-exception"),
		  scm_list_2(scm_from_locale_string(
				     ((PyTypeObject *)ptype)->tp_name),
			     pvalue_str != NULL && PyObject_IsTrue(pvalue_str)
				     ? scm_from_locale_string(
					     PyString_AsString(pvalue_str))
				     : SCM_BOOL_F));
	/* does not return */

	fprintf(stderr, "*** scm_error shouldn't have returned ***\n");
}
开发者ID:bert,项目名称:geda-gaf,代码行数:23,代码来源:py2scm.c


示例5: recursive_get_files

static int recursive_get_files(LIBMTP_mtpdevice_t *dev, uint32_t storage_id, uint32_t parent_id, PyObject *ans, PyObject *errs, PyObject *callback, unsigned int level) {
    LIBMTP_file_t *f, *files;
    PyObject *entry, *r;
    int ok = 1, recurse;

    Py_BEGIN_ALLOW_THREADS;
    files = LIBMTP_Get_Files_And_Folders(dev, storage_id, parent_id);
    Py_END_ALLOW_THREADS;

    if (files == NULL) return ok;

    for (f = files; ok && f != NULL; f = f->next) {
        entry = build_file_metadata(f, storage_id);
        if (entry == NULL) { ok = 0; }
        else {
            r = PyObject_CallFunction(callback, "OI", entry, level);
            recurse = (r != NULL && PyObject_IsTrue(r)) ? 1 : 0;
            Py_XDECREF(r);
            if (PyList_Append(ans, entry) != 0) { ok = 0; }
            Py_DECREF(entry); 
        }

        if (ok && recurse && f->filetype == LIBMTP_FILETYPE_FOLDER) {
            if (!recursive_get_files(dev, storage_id, f->item_id, ans, errs, callback, level+1)) {
                ok = 0; 
            }
        }
    }

    // Release memory
    f = files;
    while (f != NULL) {
        files = f; f = f->next; LIBMTP_destroy_file_t(files);
    }

    return ok;
}
开发者ID:AEliu,项目名称:calibre,代码行数:37,代码来源:libmtp.c


示例6: session_scp_recv

static PyObject *
session_scp_recv(SSH2_SessionObj *self, PyObject *args, PyObject *kwds)
{
	char *path;
	LIBSSH2_CHANNEL *channel;
	struct stat sb;
	PyObject* get_stat = NULL;
	int get_stat_is_true = 0;
	PyObject* chan;
	static char *kwlist[] = {"path", "get_stat", NULL};

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|O:scp_recv", kwlist,
	                                 &path, &get_stat))
		return NULL;
	if (get_stat && (get_stat_is_true = PyObject_IsTrue(get_stat)) < 0)
		return NULL;

	Py_BEGIN_ALLOW_THREADS
	channel = libssh2_scp_recv(self->session, path,
	                           get_stat_is_true ? &sb : 0);
	Py_END_ALLOW_THREADS

	CHECK_RETURN_POINTER(channel, self)

	/* Return a tuple of the channel and (size, mode, mtime, atime)
	 * of the remote file if the get_stat argument is true else return
	 * a tuple of the channel and None. */
	chan = (PyObject *)SSH2_Channel_New(channel, self);
	if (!get_stat_is_true)
		return Py_BuildValue("(OO)", chan, Py_None);

	return Py_BuildValue("(O(LlLL))", chan,
	                     (PY_LONG_LONG)sb.st_size,
	                     (long)sb.st_mode,
	                     (PY_LONG_LONG)sb.st_mtime,
	                     (PY_LONG_LONG)sb.st_atime);
}
开发者ID:vianney,项目名称:ssh4py,代码行数:37,代码来源:session.c


示例7: PyDict_GetItem

static t_link *_t_lm__get(t_lm *self, PyObject *key, int load, int noError)
{
    PyObject *link = PyDict_GetItem(self->dict, key);

    if (link == NULL)
    {
        if (load && self->flags & LM_LOAD)
        {
            PyObject *loaded =
                PyObject_CallMethodObjArgs((PyObject *) self, _load_NAME,
                                           key, NULL);

            if (!loaded)
                return NULL;

            if (PyObject_IsTrue(loaded))
                link = PyDict_GetItem(self->dict, key);

            Py_DECREF(loaded);
        }

        if (link == NULL)
        {
            if (!noError)
                PyErr_SetObject(PyExc_KeyError, key);
            return NULL;
        }
    }

    if (!PyObject_TypeCheck(link, &LinkType))
    {
        PyErr_SetObject(PyExc_TypeError, link);
        return NULL;
    }

    return (t_link *) link;
}
开发者ID:HackLinux,项目名称:chandler,代码行数:37,代码来源:linkedmap.c


示例8: bppy_set_enabled

/* Python function to set the enabled state of a breakpoint.  */
static int
bppy_set_enabled (PyObject *self, PyObject *newvalue, void *closure)
{
  gdbpy_breakpoint_object *self_bp = (gdbpy_breakpoint_object *) self;
  int cmp;

  BPPY_SET_REQUIRE_VALID (self_bp);

  if (newvalue == NULL)
    {
      PyErr_SetString (PyExc_TypeError,
		       _("Cannot delete `enabled' attribute."));

      return -1;
    }
  else if (! PyBool_Check (newvalue))
    {
      PyErr_SetString (PyExc_TypeError,
		       _("The value of `enabled' must be a boolean."));
      return -1;
    }

  cmp = PyObject_IsTrue (newvalue);
  if (cmp < 0)
    return -1;

  TRY
    {
      if (cmp == 1)
	enable_breakpoint (self_bp->bp);
      else
	disable_breakpoint (self_bp->bp);
    }
  CATCH (except, RETURN_MASK_ALL)
    {
      GDB_PY_SET_HANDLE_EXCEPTION (except);
    }
开发者ID:rmbq,项目名称:binutils-gdb,代码行数:38,代码来源:py-breakpoint.c


示例9: igraphmodule_EdgeSeq_find

/**
 * \ingroup python_interface_edgqseq
 * \brief Selects a single edge from the edge sequence based on some criteria
 */
PyObject* igraphmodule_EdgeSeq_find(igraphmodule_EdgeSeqObject *self, PyObject *args) {
  PyObject *item;
  long int i, n;

  if (!PyArg_ParseTuple(args, "O", &item))
    return NULL;

  if (PyCallable_Check(item)) {
    /* Call the callable for every edge in the current sequence and return
     * the first one for which it evaluates to True */
    n = PySequence_Size((PyObject*)self);
    for (i=0; i<n; i++) {
      PyObject *edge = PySequence_GetItem((PyObject*)self, i);
      PyObject *call_result;
      if (edge == 0)
        return NULL;
      call_result = PyObject_CallFunctionObjArgs(item, edge, NULL);
      if (call_result == 0) {
        Py_DECREF(edge);
        return NULL;
      }
      if (PyObject_IsTrue(call_result)) {
        Py_DECREF(call_result);
        return edge;  /* reference passed to caller */
      }
      Py_DECREF(call_result);
      Py_DECREF(edge);
    }
  } else if (PyInt_Check(item)) {
    /* Integers are interpreted as indices on the edge set and NOT on the
     * original, untouched edge sequence of the graph */
    return PySequence_GetItem((PyObject*)self, PyInt_AsLong(item));
  }

  PyErr_SetString(PyExc_IndexError, "no such edge");
  return NULL;
}
开发者ID:bravery,项目名称:python-igraph,代码行数:41,代码来源:edgeseqobject.c


示例10: if

static PyObject *Py_convert_to_svg(PyObject *self, PyObject *args, PyObject *kwds)
{
    py::PathIterator path;
    agg::trans_affine trans;
    agg::rect_d cliprect;
    PyObject *simplifyobj;
    bool simplify = false;
    int precision;

    if (!PyArg_ParseTuple(args,
                          "O&O&O&Oi:convert_to_svg",
                          &convert_path,
                          &path,
                          &convert_trans_affine,
                          &trans,
                          &convert_rect,
                          &cliprect,
                          &simplifyobj,
                          &precision)) {
        return NULL;
    }

    if (simplifyobj == Py_None) {
        simplify = path.should_simplify();
    } else if (PyObject_IsTrue(simplifyobj)) {
        simplify = true;
    }

    size_t buffersize = path.total_vertices() * (precision + 5) * 4;
    std::string buffer;
    buffer.reserve(buffersize);

    CALL_CPP("convert_to_svg",
             (convert_to_svg(path, trans, cliprect, simplify, precision, &buffer[0], &buffersize)));

    return PyUnicode_DecodeASCII(&buffer[0], buffersize, "");
}
开发者ID:Matt-Li,项目名称:matplotlib,代码行数:37,代码来源:_path_wrapper.cpp


示例11: already_warned

static int
already_warned(PyObject *registry, PyObject *key, int should_set)
{
    PyObject *version_obj, *already_warned;
    _Py_IDENTIFIER(version);

    if (key == NULL)
        return -1;

    version_obj = _PyDict_GetItemId(registry, &PyId_version);
    if (version_obj == NULL
        || !PyLong_CheckExact(version_obj)
        || PyLong_AsLong(version_obj) != _filters_version) {
        PyDict_Clear(registry);
        version_obj = PyLong_FromLong(_filters_version);
        if (version_obj == NULL)
            return -1;
        if (_PyDict_SetItemId(registry, &PyId_version, version_obj) < 0) {
            Py_DECREF(version_obj);
            return -1;
        }
        Py_DECREF(version_obj);
    }
    else {
        already_warned = PyDict_GetItem(registry, key);
        if (already_warned != NULL) {
            int rc = PyObject_IsTrue(already_warned);
            if (rc != 0)
                return rc;
        }
    }

    /* This warning wasn't found in the registry, set it. */
    if (should_set)
        return PyDict_SetItem(registry, key, Py_True);
    return 0;
}
开发者ID:PiJoules,项目名称:cpython-modified,代码行数:37,代码来源:_warnings.c


示例12: ConditionObject_is_owned

static PyObject*
ConditionObject_is_owned(ConditionObject *self, PyObject *args)
{
    PyObject *res, *res2;
    DEBUG("self:%p", self);

    res = call_method_args1(self->lock, "acquire", Py_False);

    if (res == NULL) {
        return NULL;
    }
    if (PyObject_IsTrue(res)) {
        Py_DECREF(res);
        res2 = call_method(self->lock, "release");
        if (res2 == NULL) {
            return NULL;
        }
        Py_DECREF(res2);
        Py_RETURN_FALSE;
    } else {
        Py_DECREF(res);
        Py_RETURN_TRUE;
    }
}
开发者ID:chenbk85,项目名称:jega,代码行数:24,代码来源:locks.c


示例13: assert

/**
 * APPisUserFeasible callback
 *
 * Called by DIP, we interface with Python
 */
bool DippyDecompApp::APPisUserFeasible(const double* x, const int n_cols, const double tolZero)
{
   assert(n_cols == m_modelCore.getModel()->getColNames().size());
   PyObject* pSolutionList = pyTupleList_FromDoubleArray(x, m_colList);
   PyObject* pTolZero = PyFloat_FromDouble(tolZero);

   if (!m_pyIsUserFeasible) {
      return true;
   }

   PyObject* pResult = PyObject_CallMethod(m_pProb, "isUserFeasible", "Od", pSolutionList, pTolZero);

   if (pResult == NULL) {
      throw UtilException("Error calling method prob.isUserFeasible()", "APPisUserFeasible", "DippyDecompApp");
   }

   // This should not happen as having isUserFeasible present but not returning a boolean is not good
   if (pResult == Py_None) {
      // method exists, but not implemented, return true
      return true;
   }

   return (bool)PyObject_IsTrue(pResult);
}
开发者ID:jiadongwang,项目名称:Dip,代码行数:29,代码来源:DippyDecompApp.cpp


示例14: __pyx_init_filenames

/* Implementation of behnel3 */

static struct PyMethodDef __pyx_methods[] = {
  {0, 0, 0, 0}
};

static void __pyx_init_filenames(void); /*proto*/

PyMODINIT_FUNC initbehnel3(void); /*proto*/
PyMODINIT_FUNC initbehnel3(void) {
  PyObject *__pyx_1 = 0;
  int __pyx_2;
  __pyx_init_filenames();
  __pyx_m = Py_InitModule4("behnel3", __pyx_methods, 0, 0, PYTHON_API_VERSION);
  if (!__pyx_m) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  Py_INCREF(__pyx_m);
  __pyx_b = PyImport_AddModule("__builtin__");
  if (!__pyx_b) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;};
  __pyx_1 = __Pyx_GetName(__pyx_b, __pyx_n_y); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}
  __pyx_2 = PyObject_IsTrue(__pyx_1); if (__pyx_2 < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}
  if (!__pyx_2) {
    Py_DECREF(__pyx_1); __pyx_1 = 0;
    __pyx_1 = PyDict_New(); if (!__pyx_1) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}
  }
  if (PyObject_SetAttr(__pyx_m, __pyx_n_x, __pyx_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; goto __pyx_L1;}
  Py_DECREF(__pyx_1); __pyx_1 = 0;
  return;
  __pyx_L1:;
  Py_XDECREF(__pyx_1);
  __Pyx_AddTraceback("behnel3");
}
开发者ID:jwilk,项目名称:Pyrex,代码行数:33,代码来源:behnel3.c


示例15: PySfImage_Copy

static PyObject *
PySfImage_Copy(PySfImage* self, PyObject *args, PyObject *kwds)
{
	const char *kwlist[] = {"Source", "DestX", "DestY", "SourceRect", "ApplyAlpha", NULL};
	PySfIntRect *SourceRect = NULL;
	PySfImage *Source = NULL;
	unsigned int DestX, DestY;
	PyObject *PyApplyAlpha = NULL;
	bool ApplyAlpha = false;

	if (!PyArg_ParseTupleAndKeywords(args, kwds, "O!II|O!O:Image.Copy", (char **)kwlist, &PySfImageType, &Source, &DestX, &DestY, &PySfIntRectType, &SourceRect, &PyApplyAlpha))
		return NULL;

	if (PyApplyAlpha)
		if (PyObject_IsTrue(PyApplyAlpha))
			ApplyAlpha = true;

	if (SourceRect)
		self->obj->Copy(*(Source->obj), DestX, DestY, *(SourceRect->obj), ApplyAlpha);
	else
		self->obj->Copy(*(Source->obj), DestX, DestY, sf::IntRect(0, 0, 0, 0), ApplyAlpha);

	Py_RETURN_NONE;
}
开发者ID:freemaul,项目名称:SFML,代码行数:24,代码来源:Image.cpp


示例16: make_safe

static PyObject *eer_threshold(PyObject *, PyObject *args, PyObject *kwds) {
  BOB_TRY
  char **kwlist = eer_threshold_doc.kwlist();

  PyBlitzArrayObject *neg;
  PyBlitzArrayObject *pos;
  PyObject *is_sorted = Py_False;

  if (!PyArg_ParseTupleAndKeywords(args, kwds, "O&O&|O", kwlist,
                                   &double1d_converter, &neg,
                                   &double1d_converter, &pos, &is_sorted))
    return 0;

  // protects acquired resources through this scope
  auto neg_ = make_safe(neg);
  auto pos_ = make_safe(pos);

  double result = bob::measure::eerThreshold(
      *PyBlitzArrayCxx_AsBlitz<double, 1>(neg),
      *PyBlitzArrayCxx_AsBlitz<double, 1>(pos), PyObject_IsTrue(is_sorted));

  return Py_BuildValue("d", result);
  BOB_CATCH_FUNCTION("eer_threshold", 0)
}
开发者ID:bioidiap,项目名称:bob.measure,代码行数:24,代码来源:main.cpp


示例17: objToJSON

PyObject* objToJSON(PyObject* self, PyObject *args, PyObject *kwargs)
{
	static char *kwlist[] = { "obj", "ensure_ascii", NULL};

	char buffer[65536];
	char *ret;
	PyObject *newobj;
	PyObject *oinput = NULL;
	PyObject *oensureAscii = NULL;

	JSONObjectEncoder encoder = 
	{
		Object_beginTypeContext,	//void (*beginTypeContext)(JSOBJ obj, JSONTypeContext *tc);
		Object_endTypeContext, //void (*endTypeContext)(JSOBJ obj, JSONTypeContext *tc);
		Object_getStringValue, //const char *(*getStringValue)(JSOBJ obj, JSONTypeContext *tc, size_t *_outLen);
		Object_getLongValue, //JSLONG (*getLongValue)(JSOBJ obj, JSONTypeContext *tc);
		Object_getIntValue, //JSLONG (*getLongValue)(JSOBJ obj, JSONTypeContext *tc);
		Object_getDoubleValue, //double (*getDoubleValue)(JSOBJ obj, JSONTypeContext *tc);
		Object_iterBegin, //JSPFN_ITERBEGIN iterBegin;
		Object_iterNext, //JSPFN_ITERNEXT iterNext;
		Object_iterEnd, //JSPFN_ITEREND iterEnd;
		Object_iterGetValue, //JSPFN_ITERGETVALUE iterGetValue;
		Object_iterGetName, //JSPFN_ITERGETNAME iterGetName;
		Object_releaseObject, //void (*releaseValue)(JSONTypeContext *ti);
		PyObject_Malloc, //JSPFN_MALLOC malloc;
		PyObject_Realloc, //JSPFN_REALLOC realloc;
		PyObject_Free, //JSPFN_FREE free;
		-1, //recursionMax
		5, //default decimal precision
		1, //forceAscii
	};
	
	PRINTMARK();

	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|O", kwlist, &oinput, &oensureAscii))
	{
		return NULL;
	}

	if (oensureAscii != NULL && !PyObject_IsTrue(oensureAscii))
	{
		encoder.forceASCII = 0;
	}

	PRINTMARK();
	ret = JSON_EncodeObject (oinput, &encoder, buffer, sizeof (buffer));
	PRINTMARK();

	if (PyErr_Occurred())
	{
		return NULL;
	}

	if (encoder.errorMsg)
	{
		if (ret != buffer)
		{
			encoder.free (ret);
		}

		PyErr_Format (PyExc_OverflowError, "%s", encoder.errorMsg);
		return NULL;
	}

	newobj = PyString_FromString (ret);

	if (ret != buffer)
	{
		encoder.free (ret);
	}

	PRINTMARK();

	return newobj;
}
开发者ID:paintcan,项目名称:ultrajson,代码行数:75,代码来源:objToJSON.c


示例18: Rules_match

static PyObject * Rules_match(
    PyObject *self,
    PyObject *args,
    PyObject *keywords)
{
  static char *kwlist[] = {
      "filepath", "pid", "data", "externals",
      "callback", "fast", "timeout", NULL
      };

  char* filepath = NULL;
  char* data = NULL;

  int pid = 0;
  int timeout = 0;
  int length;
  int error;
  int fast_mode = FALSE;

  PyObject *externals = NULL;
  PyObject *fast = NULL;
  Rules* object = (Rules*) self;

  CALLBACK_DATA callback_data;

  callback_data.matches = NULL;
  callback_data.callback = NULL;

  if (PyArg_ParseTupleAndKeywords(
        args,
        keywords,
        "|sis#OOOi",
        kwlist,
        &filepath,
        &pid,
        &data,
        &length,
        &externals,
        &callback_data.callback,
        &fast,
        &timeout))
  {
    if (externals != NULL)
    {
      if (PyDict_Check(externals))
      {
        if (!process_match_externals(externals, object->rules))
        {
          return PyErr_Format(
              PyExc_TypeError,
              "external values must be of type integer, boolean or string");
        }
      }
      else
      {
        return PyErr_Format(
            PyExc_TypeError,
            "'externals' must be a dictionary");
      }
    }

    if (callback_data.callback != NULL)
    {
      if (!PyCallable_Check(callback_data.callback))
      {
        return PyErr_Format(
            YaraError,
            "callback must be callable");
      }
    }

    if (fast != NULL)
    {
      fast_mode = (PyObject_IsTrue(fast) == 1);
    }

    if (filepath != NULL)
    {
      callback_data.matches = PyList_New(0);

      Py_BEGIN_ALLOW_THREADS

      error = yr_rules_scan_file(
          object->rules,
          filepath,
          yara_callback,
          &callback_data,
          fast_mode,
          timeout);

      Py_END_ALLOW_THREADS

      if (error != ERROR_SUCCESS)
      {
        Py_DECREF(callback_data.matches);

        if (error == ERROR_CALLBACK_ERROR)
          return NULL;
        else
          return handle_error(error, filepath);
//.........这里部分代码省略.........
开发者ID:naviduett,项目名称:yara,代码行数:101,代码来源:yara-python.c


示例19: setup_context


//.........这里部分代码省略.........
    assert(PyDict_Check(globals));
    *registry = PyDict_GetItemString(globals, "__warningregistry__");
    if (*registry == NULL) {
        int rc;

        *registry = PyDict_New();
        if (*registry == NULL)
            return 0;

         rc = PyDict_SetItemString(globals, "__warningregistry__", *registry);
         if (rc < 0)
            goto handle_error;
    }
    else
        Py_INCREF(*registry);

    /* Setup module. */
    *module = PyDict_GetItemString(globals, "__name__");
    if (*module == NULL) {
        *module = PyUnicode_FromString("<string>");
        if (*module == NULL)
            goto handle_error;
    }
    else
        Py_INCREF(*module);

    /* Setup filename. */
    *filename = PyDict_GetItemString(globals, "__file__");
    if (*filename != NULL && PyUnicode_Check(*filename)) {
        Py_ssize_t len;
        int kind;
        void *data;

        if (PyUnicode_READY(*filename))
            goto handle_error;

        len = PyUnicode_GetLength(*filename);
        kind = PyUnicode_KIND(*filename);
        data = PyUnicode_DATA(*filename);

#define ascii_lower(c) ((c <= 127) ? Py_TOLOWER(c) : 0)
        /* if filename.lower().endswith(".pyc"): */
        if (len >= 4 &&
            PyUnicode_READ(kind, data, len-4) == '.' &&
            ascii_lower(PyUnicode_READ(kind, data, len-3)) == 'p' &&
            ascii_lower(PyUnicode_READ(kind, data, len-2)) == 'y' &&
            ascii_lower(PyUnicode_READ(kind, data, len-1)) == 'c')
        {
            *filename = PyUnicode_Substring(*filename, 0,
                                            PyUnicode_GET_LENGTH(*filename)-1);
            if (*filename == NULL)
                goto handle_error;
        }
        else
            Py_INCREF(*filename);
    }
    else {
        *filename = NULL;
        if (*module != Py_None && PyUnicode_CompareWithASCIIString(*module, "__main__") == 0) {
            PyObject *argv = _PySys_GetObjectId(&PyId_argv);
            /* PyList_Check() is needed because sys.argv is set to None during
               Python finalization */
            if (argv != NULL && PyList_Check(argv) && PyList_Size(argv) > 0) {
                int is_true;
                *filename = PyList_GetItem(argv, 0);
                Py_INCREF(*filename);
                /* If sys.argv[0] is false, then use '__main__'. */
                is_true = PyObject_IsTrue(*filename);
                if (is_true < 0) {
                    Py_DECREF(*filename);
                    goto handle_error;
                }
                else if (!is_true) {
                    Py_XSETREF(*filename, PyUnicode_FromString("__main__"));
                    if (*filename == NULL)
                        goto handle_error;
                }
            }
            else {
                /* embedded interpreters don't have sys.argv, see bug #839151 */
                *filename = PyUnicode_FromString("__main__");
                if (*filename == NULL)
                    goto handle_error;
            }
        }
        if (*filename == NULL) {
            *filename = *module;
            Py_INCREF(*filename);
        }
    }

    return 1;

 handle_error:
    /* filename not XDECREF'ed here as there is no way to jump here with a
       dangling reference. */
    Py_XDECREF(*registry);
    Py_XDECREF(*module);
    return 0;
}
开发者ID:PiJoules,项目名称:cpython-modified,代码行数:101,代码来源:_warnings.c


示例20: PySys_GetFile

static PyObject *builder_parse(PyObject *inputSource, ParseFlags flags,
                               PyObject *entity_factory, int asEntity,
                               PyObject *namespaces, PyObject *rule_handler)
{
  ParserState *state;
  PyObject *result;
  int gc_enabled;
  ExpatStatus status;

#ifdef DEBUG_PARSER
  FILE *stream = PySys_GetFile("stderr", stderr);
  PySys_WriteStderr("builder_parse(source=");
  PyObject_Print(inputSource, stream, 0);
  PySys_WriteStderr(", flags=%d, entity_factory=", flags);
  PyObject_Print(entity_factory, stream, 0);
  PySys_WriteStderr(", asEntity=%d, namespaces=", asEntity);
  PyObject_Print(namespaces, stream, 0);
  PySys_WriteStderr("\n");
#endif
  state = ParserState_New(entity_factory);
  if (state == NULL)
    return NULL;

  state->reader = create_reader(state);
  if (state->reader == NULL) {
    ParserState_Del(state);
    return NULL;
  }

  if (rule_handler) {
    state->rule_matcher = RuleMatchObject_New(rule_handler);
  }

  /* Disable GC (if enabled) while building the DOM tree */
  result = PyObject_Call(gc_isenabled_function, empty_args_tuple, NULL);
  if (result == NULL)
    goto finally;
  gc_enabled = PyObject_IsTrue(result);
  Py_DECREF(result);
  if (gc_enabled) {
    result = PyObject_Call(gc_disable_function, empty_args_tuple, NULL);
    if (result == NULL)
      goto finally;
    Py_DECREF(result);
  }

  Expat_SetValidation(state->reader, flags == PARSE_FLAGS_VALIDATE);
  Expat_SetParamEntityParsing(state->reader, flags != PARSE_FLAGS_STANDALONE);

  if (asEntity)
    status = ExpatReader_ParseEntity(state->reader, inputSource, namespaces);
  else
    status = ExpatReader_Parse(state->reader, inputSource);

  if (gc_enabled) {
    result = PyObject_Call(gc_enable_function, empty_args_tuple, NULL);
    if (result == NULL)
      goto finally;
    Py_DECREF(result);
  }

  /* save off the created document */
  if (status == EXPAT_STATUS_OK)
    result = (PyObject *)state->owner_document;
  else
    result = NULL;

finally:
  ExpatReader_Del(state->reader);
  ParserState_Del(state);
#ifdef DEBUG_PARSER
  PySys_WriteStderr("builder_parse() => ");
  PyObject_Print(result, PySys_GetFile("stderr", stderr), 0);
  PySys_WriteStderr("\n");
#endif
  return result;
}
开发者ID:abed-hawa,项目名称:amara,代码行数:77,代码来源:builder.c



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

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