本文整理汇总了C++中PyErr_SetString函数的典型用法代码示例。如果您正苦于以下问题:C++ PyErr_SetString函数的具体用法?C++ PyErr_SetString怎么用?C++ PyErr_SetString使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyErr_SetString函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: int
static PyObject *py_sorted_tree_items(PyObject *self, PyObject *args)
{
struct tree_item *qsort_entries = NULL;
int name_order, num_entries, n = 0, i;
PyObject *entries, *py_name_order, *ret, *key, *value, *py_mode, *py_sha;
Py_ssize_t pos = 0;
int (*cmp)(const void *, const void *);
if (!PyArg_ParseTuple(args, "OO", &entries, &py_name_order))
goto error;
if (!PyDict_Check(entries)) {
PyErr_SetString(PyExc_TypeError, "Argument not a dictionary");
goto error;
}
name_order = PyObject_IsTrue(py_name_order);
if (name_order == -1)
goto error;
cmp = name_order ? cmp_tree_item_name_order : cmp_tree_item;
num_entries = PyDict_Size(entries);
if (PyErr_Occurred())
goto error;
qsort_entries = PyMem_New(struct tree_item, num_entries);
if (!qsort_entries) {
PyErr_NoMemory();
goto error;
}
while (PyDict_Next(entries, &pos, &key, &value)) {
if (!PyString_Check(key)) {
PyErr_SetString(PyExc_TypeError, "Name is not a string");
goto error;
}
if (PyTuple_Size(value) != 2) {
PyErr_SetString(PyExc_ValueError, "Tuple has invalid size");
goto error;
}
py_mode = PyTuple_GET_ITEM(value, 0);
if (!PyInt_Check(py_mode)) {
PyErr_SetString(PyExc_TypeError, "Mode is not an integral type");
goto error;
}
py_sha = PyTuple_GET_ITEM(value, 1);
if (!PyString_Check(py_sha)) {
PyErr_SetString(PyExc_TypeError, "SHA is not a string");
goto error;
}
qsort_entries[n].name = PyString_AS_STRING(key);
qsort_entries[n].mode = PyInt_AS_LONG(py_mode);
qsort_entries[n].tuple = PyObject_CallFunctionObjArgs(
tree_entry_cls, key, py_mode, py_sha, NULL);
if (qsort_entries[n].tuple == NULL)
goto error;
n++;
}
qsort(qsort_entries, num_entries, sizeof(struct tree_item), cmp);
ret = PyList_New(num_entries);
if (ret == NULL) {
PyErr_NoMemory();
goto error;
}
for (i = 0; i < num_entries; i++) {
PyList_SET_ITEM(ret, i, qsort_entries[i].tuple);
}
PyMem_Free(qsort_entries);
return ret;
error:
for (i = 0; i < n; i++) {
Py_XDECREF(qsort_entries[i].tuple);
}
PyMem_Free(qsort_entries);
return NULL;
}
示例2: PyErr_SetString
static PyObject *Consumer_consume (Handle *self, PyObject *args,
PyObject *kwargs) {
unsigned int num_messages = 1;
double tmout = -1.0f;
static char *kws[] = { "num_messages", "timeout", NULL };
rd_kafka_message_t **rkmessages;
PyObject *msglist;
rd_kafka_queue_t *rkqu = self->u.Consumer.rkqu;
CallState cs;
Py_ssize_t i, n;
if (!self->rk) {
PyErr_SetString(PyExc_RuntimeError,
"Consumer closed");
return NULL;
}
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|Id", kws,
&num_messages, &tmout))
return NULL;
if (num_messages > 1000000) {
PyErr_SetString(PyExc_ValueError,
"num_messages must be between 0 and 1000000 (1M)");
return NULL;
}
CallState_begin(self, &cs);
rkmessages = malloc(num_messages * sizeof(rd_kafka_message_t *));
n = (Py_ssize_t)rd_kafka_consume_batch_queue(rkqu,
tmout >= 0 ? (int)(tmout * 1000.0f) : -1,
rkmessages,
num_messages);
if (!CallState_end(self, &cs)) {
for (i = 0; i < n; i++) {
rd_kafka_message_destroy(rkmessages[i]);
}
free(rkmessages);
return NULL;
}
if (n < 0) {
free(rkmessages);
cfl_PyErr_Format(rd_kafka_last_error(),
"%s", rd_kafka_err2str(rd_kafka_last_error()));
return NULL;
}
msglist = PyList_New(n);
for (i = 0; i < n; i++) {
PyObject *msgobj = Message_new0(self, rkmessages[i]);
#ifdef RD_KAFKA_V_HEADERS
// Have to detach headers outside Message_new0 because it declares the
// rk message as a const
rd_kafka_message_detach_headers(rkmessages[i], &((Message *)msgobj)->c_headers);
#endif
PyList_SET_ITEM(msglist, i, msgobj);
rd_kafka_message_destroy(rkmessages[i]);
}
free(rkmessages);
return msglist;
}
示例3: load_next
/* altmod is either None or same as mod */
static PyObject *
load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
int *p_buflen)
{
char *name = *p_name;
char *dot = strchr(name, '.');
size_t len;
char *p;
PyObject *result;
if (dot == NULL) {
*p_name = NULL;
len = strlen(name);
}
else {
*p_name = dot+1;
len = dot-name;
}
if (len == 0) {
PyErr_SetString(PyExc_ValueError,
"Empty module name");
return NULL;
}
p = buf + *p_buflen;
if (p != buf)
*p++ = '.';
if (p+len-buf >= MAXPATHLEN) {
PyErr_SetString(PyExc_ValueError,
"Module name too long");
return NULL;
}
strncpy(p, name, len);
p[len] = '\0';
*p_buflen = p+len-buf;
result = import_submodule(mod, p, buf);
if (result == Py_None && altmod != mod) {
Py_DECREF(result);
/* Here, altmod must be None and mod must not be None */
result = import_submodule(altmod, p, p);
if (result != NULL && result != Py_None) {
if (mark_miss(buf) != 0) {
Py_DECREF(result);
return NULL;
}
strncpy(buf, name, len);
buf[len] = '\0';
*p_buflen = len;
}
}
if (result == NULL)
return NULL;
if (result == Py_None) {
Py_DECREF(result);
PyErr_Format(PyExc_ImportError,
"No module named %.200s", name);
return NULL;
}
return result;
}
示例4: PyErr_Clear
static PyObject *_read_png(PyObject *filein, bool float_result)
{
png_byte header[8]; // 8 is the maximum size that can be checked
FILE *fp = NULL;
mpl_off_t offset = 0;
bool close_file = false;
bool close_dup_file = false;
PyObject *py_file = NULL;
png_structp png_ptr = NULL;
png_infop info_ptr = NULL;
int num_dims;
std::vector<png_bytep> row_pointers;
png_uint_32 width = 0;
png_uint_32 height = 0;
int bit_depth;
PyObject *result = NULL;
// TODO: Remove direct calls to Numpy API here
if (PyBytes_Check(filein) || PyUnicode_Check(filein)) {
if ((py_file = mpl_PyFile_OpenFile(filein, (char *)"rb")) == NULL) {
goto exit;
}
close_file = true;
} else {
py_file = filein;
}
if ((fp = mpl_PyFile_Dup(py_file, (char *)"rb", &offset))) {
close_dup_file = true;
} else {
PyErr_Clear();
PyObject *read_method = PyObject_GetAttrString(py_file, "read");
if (!(read_method && PyCallable_Check(read_method))) {
Py_XDECREF(read_method);
PyErr_SetString(PyExc_TypeError,
"Object does not appear to be a 8-bit string path or "
"a Python file-like object");
goto exit;
}
Py_XDECREF(read_method);
}
if (fp) {
if (fread(header, 1, 8, fp) != 8) {
PyErr_SetString(PyExc_IOError, "error reading PNG header");
goto exit;
}
} else {
_read_png_data(py_file, header, 8);
}
if (png_sig_cmp(header, 0, 8)) {
PyErr_SetString(PyExc_ValueError, "invalid PNG header");
goto exit;
}
/* initialize stuff */
png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (!png_ptr) {
PyErr_SetString(PyExc_RuntimeError, "png_create_read_struct failed");
goto exit;
}
info_ptr = png_create_info_struct(png_ptr);
if (!info_ptr) {
PyErr_SetString(PyExc_RuntimeError, "png_create_info_struct failed");
goto exit;
}
if (setjmp(png_jmpbuf(png_ptr))) {
PyErr_SetString(PyExc_RuntimeError, "Error setting jump");
goto exit;
}
if (fp) {
png_init_io(png_ptr, fp);
} else {
png_set_read_fn(png_ptr, (void *)py_file, &read_png_data);
}
png_set_sig_bytes(png_ptr, 8);
png_read_info(png_ptr, info_ptr);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
// Unpack 1, 2, and 4-bit images
if (bit_depth < 8) {
png_set_packing(png_ptr);
}
// If sig bits are set, shift data
png_color_8p sig_bit;
if ((png_get_color_type(png_ptr, info_ptr) != PNG_COLOR_TYPE_PALETTE) &&
png_get_sBIT(png_ptr, info_ptr, &sig_bit)) {
png_set_shift(png_ptr, sig_bit);
}
//.........这里部分代码省略.........
示例5: kbe_snprintf
//-------------------------------------------------------------------------------------
void Proxy::giveClientTo(Proxy* proxy)
{
if(isDestroyed())
{
char err[255];
kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: %d is destroyed.",
getScriptName(), getID());
PyErr_SetString(PyExc_TypeError, err);
PyErr_PrintEx(0);
onGiveClientToFailure();
return;
}
if(clientMailbox_ == NULL || clientMailbox_->getChannel() == NULL)
{
char err[255];
kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: no has client.", getScriptName());
PyErr_SetString(PyExc_TypeError, err);
PyErr_PrintEx(0);
onGiveClientToFailure();
return;
}
Mercury::Channel* lpChannel = clientMailbox_->getChannel();
if(proxy)
{
if(proxy->isDestroyed())
{
char err[255];
kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: target(%d) is destroyed.",
getScriptName(), proxy->getID());
PyErr_SetString(PyExc_TypeError, err);
PyErr_PrintEx(0);
onGiveClientToFailure();
return;
}
if(proxy->getID() == this->getID())
{
char err[255];
kbe_snprintf(err, 255, "Proxy[%s]::giveClientTo: target(%d) is self.",
getScriptName(), proxy->getID());
PyErr_SetString(PyExc_TypeError, err);
PyErr_PrintEx(0);
onGiveClientToFailure();
return;
}
EntityMailbox* mb = proxy->getClientMailbox();
if(mb != NULL)
{
ERROR_MSG(boost::format("Proxy::giveClientTo: %1%[%2%] give client to %3%[%4%], %5% has clientMailbox.\n") %
getScriptName() %
getID() %
proxy->getScriptName() %
proxy->getID() %
proxy->getScriptName());
onGiveClientToFailure();
return;
}
if(getCellMailbox())
{
// 通知cell丢失客户端
Mercury::Bundle* pBundle = Mercury::Bundle::ObjPool().createObject();
(*pBundle).newMessage(CellappInterface::onResetWitness);
(*pBundle) << this->getID();
getCellMailbox()->postMail((*pBundle));
Mercury::Bundle::ObjPool().reclaimObject(pBundle);
}
entitiesEnabled_ = false;
getClientMailbox()->addr(Mercury::Address::NONE);
Py_DECREF(getClientMailbox());
proxy->onGiveClientTo(lpChannel);
setClientMailbox(NULL);
addr(Mercury::Address::NONE);
if(proxy->getClientMailbox() != NULL)
{
// 通知client销毁当前entity
Mercury::Bundle* pBundle = Mercury::Bundle::ObjPool().createObject();
(*pBundle).newMessage(ClientInterface::onEntityDestroyed);
(*pBundle) << this->getID();
proxy->sendToClient(ClientInterface::onEntityDestroyed, pBundle);
//Mercury::Bundle::ObjPool().reclaimObject(pBundle);
}
}
}
示例6: option
//.........这里部分代码省略.........
if (error < 0)
return Error_set(error);
Py_RETURN_NONE;
}
case GIT_OPT_GET_CACHED_MEMORY:
{
size_t current;
size_t allowed;
PyObject* tup = PyTuple_New(2);
error = git_libgit2_opts(GIT_OPT_GET_CACHED_MEMORY, ¤t, &allowed);
if (error < 0)
return Error_set(error);
PyTuple_SetItem(tup, 0, PyInt_FromLong(current));
PyTuple_SetItem(tup, 1, PyInt_FromLong(allowed));
return tup;
}
case GIT_OPT_SET_SSL_CERT_LOCATIONS:
{
PyObject *py_file, *py_dir;
const char *file_path, *dir_path;
int err;
py_file = PyTuple_GetItem(args, 1);
py_dir = PyTuple_GetItem(args, 2);
/* py_file and py_dir are only valid if they are strings */
if (PyUnicode_Check(py_file) || PyBytes_Check(py_file)) {
file_path = py_str_to_c_str(py_file, Py_FileSystemDefaultEncoding);
} else {
file_path = NULL;
}
if (PyUnicode_Check(py_dir) || PyBytes_Check(py_dir)) {
dir_path = py_str_to_c_str(py_dir, Py_FileSystemDefaultEncoding);
} else {
dir_path = NULL;
}
err = git_libgit2_opts(GIT_OPT_SET_SSL_CERT_LOCATIONS, file_path, dir_path);
if (err < 0)
return Error_set(err);
Py_RETURN_NONE;
}
// int enabled
case GIT_OPT_ENABLE_CACHING:
case GIT_OPT_ENABLE_STRICT_OBJECT_CREATION:
case GIT_OPT_ENABLE_STRICT_SYMBOLIC_REF_CREATION:
case GIT_OPT_ENABLE_OFS_DELTA:
case GIT_OPT_ENABLE_FSYNC_GITDIR:
case GIT_OPT_ENABLE_STRICT_HASH_VERIFICATION:
case GIT_OPT_ENABLE_UNSAVED_INDEX_SAFETY:
{
PyObject *py_enabled;
int enabled;
py_enabled = PyTuple_GetItem(args, 1);
if (!py_enabled)
return NULL;
if (!PyInt_Check(py_enabled))
return Error_type_error("expected integer, got %.200s", py_enabled);
enabled = PyInt_AsSize_t(py_enabled);
error = git_libgit2_opts(option, enabled);
if (error < 0)
return Error_set(error);
Py_RETURN_NONE;
}
// Not implemented
case GIT_OPT_GET_TEMPLATE_PATH:
case GIT_OPT_SET_TEMPLATE_PATH:
case GIT_OPT_SET_USER_AGENT:
case GIT_OPT_SET_SSL_CIPHERS:
case GIT_OPT_GET_USER_AGENT:
case GIT_OPT_GET_WINDOWS_SHAREMODE:
case GIT_OPT_SET_WINDOWS_SHAREMODE:
case GIT_OPT_SET_ALLOCATOR:
case GIT_OPT_GET_PACK_MAX_OBJECTS:
case GIT_OPT_SET_PACK_MAX_OBJECTS:
{
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
}
PyErr_SetString(PyExc_ValueError, "unknown/unsupported option value");
return NULL;
}
示例7: PyObject_Dir
PyObject *
PyObject_Dir(PyObject *arg)
{
/* Set exactly one of these non-NULL before the end. */
PyObject *result = NULL; /* result list */
PyObject *masterdict = NULL; /* result is masterdict.keys() */
/* If NULL arg, return the locals. */
if (arg == NULL) {
PyObject *locals = PyEval_GetLocals();
if (locals == NULL)
goto error;
result = PyMapping_Keys(locals);
if (result == NULL)
goto error;
}
/* Elif this is some form of module, we only want its dict. */
else if (PyModule_Check(arg)) {
masterdict = PyObject_GetAttrString(arg, "__dict__");
if (masterdict == NULL)
goto error;
if (!PyDict_Check(masterdict)) {
PyErr_SetString(PyExc_TypeError,
"module.__dict__ is not a dictionary");
goto error;
}
}
/* Elif some form of type or class, grab its dict and its bases.
We deliberately don't suck up its __class__, as methods belonging
to the metaclass would probably be more confusing than helpful. */
else if (PyType_Check(arg) || PyClass_Check(arg)) {
masterdict = PyDict_New();
if (masterdict == NULL)
goto error;
if (merge_class_dict(masterdict, arg) < 0)
goto error;
}
/* Else look at its dict, and the attrs reachable from its class. */
else {
PyObject *itsclass;
/* Create a dict to start with. CAUTION: Not everything
responding to __dict__ returns a dict! */
masterdict = PyObject_GetAttrString(arg, "__dict__");
if (masterdict == NULL) {
PyErr_Clear();
masterdict = PyDict_New();
}
else if (!PyDict_Check(masterdict)) {
Py_DECREF(masterdict);
masterdict = PyDict_New();
}
else {
/* The object may have returned a reference to its
dict, so copy it to avoid mutating it. */
PyObject *temp = PyDict_Copy(masterdict);
Py_DECREF(masterdict);
masterdict = temp;
}
if (masterdict == NULL)
goto error;
/* Merge in __members__ and __methods__ (if any).
XXX Would like this to go away someday; for now, it's
XXX needed to get at im_self etc of method objects. */
if (merge_list_attr(masterdict, arg, "__members__") < 0)
goto error;
if (merge_list_attr(masterdict, arg, "__methods__") < 0)
goto error;
/* Merge in attrs reachable from its class.
CAUTION: Not all objects have a __class__ attr. */
itsclass = PyObject_GetAttrString(arg, "__class__");
if (itsclass == NULL)
PyErr_Clear();
else {
int status = merge_class_dict(masterdict, itsclass);
Py_DECREF(itsclass);
if (status < 0)
goto error;
}
}
assert((result == NULL) ^ (masterdict == NULL));
if (masterdict != NULL) {
/* The result comes from its keys. */
assert(result == NULL);
result = PyDict_Keys(masterdict);
if (result == NULL)
goto error;
}
assert(result);
if (!PyList_Check(result)) {
PyErr_Format(PyExc_TypeError,
"Expected keys() to be a list, not '%.200s'",
result->ob_type->tp_name);
goto error;
//.........这里部分代码省略.........
示例8: encode_unicode
/*
* This function is an almost verbatim copy of unicodeescape_string() from
* Python's unicodeobject.c with the following differences:
*
* - it always quotes the output using double quotes.
* - it uses \u00hh instead of \xhh in output.
* - it also quotes \b and \f
*/
static PyObject*
encode_unicode(PyObject *unicode)
{
PyObject *repr;
Py_UNICODE *s;
Py_ssize_t size;
char *p;
static const char *hexdigit = "0123456789abcdef";
s = PyUnicode_AS_UNICODE(unicode);
size = PyUnicode_GET_SIZE(unicode);
if (size > (PY_SSIZE_T_MAX-2-1)/6) {
PyErr_SetString(PyExc_OverflowError,
"unicode object is too large to make repr");
return NULL;
}
repr = PyString_FromStringAndSize(NULL, 2 + 6*size + 1);
if (repr == NULL)
return NULL;
p = PyString_AS_STRING(repr);
*p++ = '"';
while (size-- > 0) {
Py_UNICODE ch = *s++;
/* Escape quotes */
if ((ch == (Py_UNICODE) PyString_AS_STRING(repr)[0] || ch == '\\')) {
*p++ = '\\';
*p++ = (char) ch;
continue;
}
#ifdef Py_UNICODE_WIDE
/* Map 21-bit characters to '\U00xxxxxx' */
else if (ch >= 0x10000) {
int offset = p - PyString_AS_STRING(repr);
/* Resize the string if necessary */
if (offset + 12 > PyString_GET_SIZE(repr)) {
if (_PyString_Resize(&repr, PyString_GET_SIZE(repr) + 100))
return NULL;
p = PyString_AS_STRING(repr) + offset;
}
*p++ = '\\';
*p++ = 'U';
*p++ = hexdigit[(ch >> 28) & 0x0000000F];
*p++ = hexdigit[(ch >> 24) & 0x0000000F];
*p++ = hexdigit[(ch >> 20) & 0x0000000F];
*p++ = hexdigit[(ch >> 16) & 0x0000000F];
*p++ = hexdigit[(ch >> 12) & 0x0000000F];
*p++ = hexdigit[(ch >> 8) & 0x0000000F];
*p++ = hexdigit[(ch >> 4) & 0x0000000F];
*p++ = hexdigit[ch & 0x0000000F];
continue;
}
#endif
/* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
else if (ch >= 0xD800 && ch < 0xDC00) {
示例9: psutil_net_io_counters
/*
* Return a list of tuples for network I/O statistics.
*/
static PyObject *
psutil_net_io_counters(PyObject *self, PyObject *args)
{
kstat_ctl_t *kc = NULL;
kstat_t *ksp;
kstat_named_t *rbytes, *wbytes, *rpkts, *wpkts, *ierrs, *oerrs;
PyObject *py_retdict = PyDict_New();
PyObject *py_ifc_info = NULL;
if (py_retdict == NULL)
return NULL;
kc = kstat_open();
if (kc == NULL)
goto error;
ksp = kc->kc_chain;
while (ksp != NULL) {
if (ksp->ks_type != KSTAT_TYPE_NAMED)
goto next;
if (strcmp(ksp->ks_class, "net") != 0)
goto next;
/*
// XXX "lo" (localhost) interface makes kstat_data_lookup() fail
// (maybe because "ifconfig -a" says it's a virtual interface?).
if ((strcmp(ksp->ks_module, "link") != 0) &&
(strcmp(ksp->ks_module, "lo") != 0)) {
goto skip;
*/
if ((strcmp(ksp->ks_module, "link") != 0)) {
goto next;
}
if (kstat_read(kc, ksp, NULL) == -1) {
errno = 0;
continue;
}
rbytes = (kstat_named_t *)kstat_data_lookup(ksp, "rbytes");
wbytes = (kstat_named_t *)kstat_data_lookup(ksp, "obytes");
rpkts = (kstat_named_t *)kstat_data_lookup(ksp, "ipackets");
wpkts = (kstat_named_t *)kstat_data_lookup(ksp, "opackets");
ierrs = (kstat_named_t *)kstat_data_lookup(ksp, "ierrors");
oerrs = (kstat_named_t *)kstat_data_lookup(ksp, "oerrors");
if ((rbytes == NULL) || (wbytes == NULL) || (rpkts == NULL) ||
(wpkts == NULL) || (ierrs == NULL) || (oerrs == NULL))
{
PyErr_SetString(PyExc_RuntimeError, "kstat_data_lookup() failed");
goto error;
}
#if defined(_INT64_TYPE)
py_ifc_info = Py_BuildValue("(KKKKkkii)",
rbytes->value.ui64,
wbytes->value.ui64,
rpkts->value.ui64,
wpkts->value.ui64,
ierrs->value.ui32,
oerrs->value.ui32,
#else
py_ifc_info = Py_BuildValue("(kkkkkkii)",
rbytes->value.ui32,
wbytes->value.ui32,
rpkts->value.ui32,
wpkts->value.ui32,
ierrs->value.ui32,
oerrs->value.ui32,
#endif
0, // dropin not supported
0 // dropout not supported
);
if (!py_ifc_info)
goto error;
if (PyDict_SetItemString(py_retdict, ksp->ks_name, py_ifc_info))
goto error;
Py_DECREF(py_ifc_info);
goto next;
next:
ksp = ksp->ks_next;
}
kstat_close(kc);
return py_retdict;
error:
Py_XDECREF(py_ifc_info);
Py_DECREF(py_retdict);
if (kc != NULL)
kstat_close(kc);
return NULL;
}
示例10: psutil_net_connections
/*
* Return TCP and UDP connections opened by process.
* UNIX sockets are excluded.
*
* Thanks to:
* https://github.com/DavidGriffith/finx/blob/master/
* nxsensor-3.5.0-1/src/sysdeps/solaris.c
* ...and:
* https://hg.java.net/hg/solaris~on-src/file/tip/usr/src/cmd/
* cmd-inet/usr.bin/netstat/netstat.c
*/
static PyObject *
psutil_net_connections(PyObject *self, PyObject *args)
{
long pid;
int sd = NULL;
mib2_tcpConnEntry_t *tp = NULL;
mib2_udpEntry_t *ude;
#if defined(AF_INET6)
mib2_tcp6ConnEntry_t *tp6;
mib2_udp6Entry_t *ude6;
#endif
char buf[512];
int i, flags, getcode, num_ent, state;
char lip[200], rip[200];
int lport, rport;
int processed_pid;
struct strbuf ctlbuf, databuf;
struct T_optmgmt_req *tor = (struct T_optmgmt_req *)buf;
struct T_optmgmt_ack *toa = (struct T_optmgmt_ack *)buf;
struct T_error_ack *tea = (struct T_error_ack *)buf;
struct opthdr *mibhdr;
PyObject *py_retlist = PyList_New(0);
PyObject *py_tuple = NULL;
PyObject *py_laddr = NULL;
PyObject *py_raddr = NULL;
PyObject *af_filter = NULL;
PyObject *type_filter = NULL;
if (py_retlist == NULL)
return NULL;
if (! PyArg_ParseTuple(args, "lOO", &pid, &af_filter, &type_filter))
goto error;
if (!PySequence_Check(af_filter) || !PySequence_Check(type_filter)) {
PyErr_SetString(PyExc_TypeError, "arg 2 or 3 is not a sequence");
goto error;
}
sd = open("/dev/arp", O_RDWR);
if (sd == -1) {
PyErr_SetFromErrnoWithFilename(PyExc_OSError, "/dev/arp");
goto error;
}
/*
XXX - These 2 are used in ifconfig.c but they seem unnecessary
ret = ioctl(sd, I_PUSH, "tcp");
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
ret = ioctl(sd, I_PUSH, "udp");
if (ret == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
*/
// OK, this mess is basically copied and pasted from nxsensor project
// which copied and pasted it from netstat source code, mibget()
// function. Also see:
// http://stackoverflow.com/questions/8723598/
tor->PRIM_type = T_SVR4_OPTMGMT_REQ;
tor->OPT_offset = sizeof (struct T_optmgmt_req);
tor->OPT_length = sizeof (struct opthdr);
tor->MGMT_flags = T_CURRENT;
mibhdr = (struct opthdr *)&tor[1];
mibhdr->level = EXPER_IP_AND_ALL_IRES;
mibhdr->name = 0;
mibhdr->len = 0;
ctlbuf.buf = buf;
ctlbuf.len = tor->OPT_offset + tor->OPT_length;
flags = 0; // request to be sent in non-priority
if (putmsg(sd, &ctlbuf, (struct strbuf *)0, flags) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
goto error;
}
mibhdr = (struct opthdr *)&toa[1];
ctlbuf.maxlen = sizeof (buf);
for (;;) {
flags = 0;
getcode = getmsg(sd, &ctlbuf, (struct strbuf *)0, &flags);
if (getcode != MOREDATA ||
ctlbuf.len < sizeof (struct T_optmgmt_ack) ||
//.........这里部分代码省略.........
示例11: psutil_swap_mem
/*
* Return information about system virtual memory.
*/
static PyObject *
psutil_swap_mem(PyObject *self, PyObject *args)
{
// XXX (arghhh!)
// total/free swap mem: commented out as for some reason I can't
// manage to get the same results shown by "swap -l", despite the
// code below is exactly the same as:
// http://cvs.opensolaris.org/source/xref/onnv/onnv-gate/usr/src/
// cmd/swap/swap.c
// We're going to parse "swap -l" output from Python (sigh!)
/*
struct swaptable *st;
struct swapent *swapent;
int i;
struct stat64 statbuf;
char *path;
char fullpath[MAXPATHLEN+1];
int num;
if ((num = swapctl(SC_GETNSWP, NULL)) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
if (num == 0) {
PyErr_SetString(PyExc_RuntimeError, "no swap devices configured");
return NULL;
}
if ((st = malloc(num * sizeof(swapent_t) + sizeof (int))) == NULL) {
PyErr_SetString(PyExc_RuntimeError, "malloc failed");
return NULL;
}
if ((path = malloc(num * MAXPATHLEN)) == NULL) {
PyErr_SetString(PyExc_RuntimeError, "malloc failed");
return NULL;
}
swapent = st->swt_ent;
for (i = 0; i < num; i++, swapent++) {
swapent->ste_path = path;
path += MAXPATHLEN;
}
st->swt_n = num;
if ((num = swapctl(SC_LIST, st)) == -1) {
PyErr_SetFromErrno(PyExc_OSError);
return NULL;
}
swapent = st->swt_ent;
long t = 0, f = 0;
for (i = 0; i < num; i++, swapent++) {
int diskblks_per_page =(int)(sysconf(_SC_PAGESIZE) >> DEV_BSHIFT);
t += (long)swapent->ste_pages;
f += (long)swapent->ste_free;
}
free(st);
return Py_BuildValue("(kk)", t, f);
*/
kstat_ctl_t *kc;
kstat_t *k;
cpu_stat_t *cpu;
int cpu_count = 0;
int flag = 0;
uint_t sin = 0;
uint_t sout = 0;
kc = kstat_open();
if (kc == NULL) {
return PyErr_SetFromErrno(PyExc_OSError);;
}
k = kc->kc_chain;
while (k != NULL) {
if ((strncmp(k->ks_name, "cpu_stat", 8) == 0) && \
(kstat_read(kc, k, NULL) != -1) )
{
flag = 1;
cpu = (cpu_stat_t *) k->ks_data;
sin += cpu->cpu_vminfo.pgswapin; // num pages swapped in
sout += cpu->cpu_vminfo.pgswapout; // num pages swapped out
}
cpu_count += 1;
k = k->ks_next;
}
kstat_close(kc);
if (!flag) {
PyErr_SetString(PyExc_RuntimeError, "no swap device was found");
return NULL;
}
return Py_BuildValue("(II)", sin, sout);
}
示例12: superlu_python_module_abort
void superlu_python_module_abort(char *msg)
{
PyErr_SetString(PyExc_RuntimeError, msg);
longjmp(_superlu_py_jmpbuf, -1);
}
示例13: PyObject_IsTrue
static PyObject *py_parse_tree(PyObject *self, PyObject *args, PyObject *kw)
{
char *text, *start, *end;
int len, namelen, strict;
PyObject *ret, *item, *name, *sha, *py_strict = NULL;
static char *kwlist[] = {"text", "strict", NULL};
if (!PyArg_ParseTupleAndKeywords(args, kw, "s#|O", kwlist,
&text, &len, &py_strict))
return NULL;
strict = py_strict ? PyObject_IsTrue(py_strict) : 0;
/* 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;
if (strict && text[0] == '0') {
PyErr_SetString(object_format_exception_cls,
"Illegal leading zero on mode");
Py_DECREF(ret);
return NULL;
}
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;
}
sha = sha_to_pyhex((unsigned char *)text+namelen+1);
if (sha == NULL) {
Py_DECREF(ret);
Py_DECREF(name);
return NULL;
}
item = Py_BuildValue("(NlN)", name, mode, sha);
if (item == NULL) {
Py_DECREF(ret);
Py_DECREF(sha);
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;
}
示例14: complex_richcompare
static PyObject *
complex_richcompare(PyObject *v, PyObject *w, int op)
{
PyObject *res;
Py_complex i;
int equal;
if (op != Py_EQ && op != Py_NE) {
/* for backwards compatibility, comparisons with non-numbers return
* NotImplemented. Only comparisons with core numeric types raise
* TypeError.
*/
if (PyInt_Check(w) || PyLong_Check(w) ||
PyFloat_Check(w) || PyComplex_Check(w)) {
PyErr_SetString(PyExc_TypeError,
"no ordering relation is defined "
"for complex numbers");
return NULL;
}
goto Unimplemented;
}
assert(PyComplex_Check(v));
TO_COMPLEX(v, i);
if (PyInt_Check(w) || PyLong_Check(w)) {
/* Check for 0.0 imaginary part first to avoid the rich
* comparison when possible.
*/
if (i.imag == 0.0) {
PyObject *j, *sub_res;
j = PyFloat_FromDouble(i.real);
if (j == NULL)
return NULL;
sub_res = PyObject_RichCompare(j, w, op);
Py_DECREF(j);
return sub_res;
}
else {
equal = 0;
}
}
else if (PyFloat_Check(w)) {
equal = (i.real == PyFloat_AsDouble(w) && i.imag == 0.0);
}
else if (PyComplex_Check(w)) {
Py_complex j;
TO_COMPLEX(w, j);
equal = (i.real == j.real && i.imag == j.imag);
}
else {
goto Unimplemented;
}
if (equal == (op == Py_EQ))
res = Py_True;
else
res = Py_False;
Py_INCREF(res);
return res;
Unimplemented:
Py_INCREF(Py_NotImplemented);
return Py_NotImplemented;
}
示例15: PyErr_SetString
PyObject *scribus_createcustomlinestyle(PyObject * /* self */, PyObject* args)
{
char *Name = const_cast<char*>("");
PyObject *obj;
if (!PyArg_ParseTuple(args, "esO", "utf-8", &Name, &obj))
return NULL;
if (!PyList_Check(obj)) {
PyErr_SetString(PyExc_TypeError, "'style' must be list.");
return NULL;
}
multiLine ml;
for (int i = 0; i < PyList_Size(obj); i++) {
PyObject *line = PyList_GetItem(obj, i);
if (!PyDict_Check(line)) {
PyErr_SetString(PyExc_TypeError, "elements of list must be Dictionary.");
return NULL;
}
struct SingleLine sl;
PyObject *val;
val = PyDict_GetItemString(line, "Color");
if (val) {
sl.Color = PyString_AsString(val);
} else
sl.Color = ScCore->primaryMainWindow()->doc->itemToolPrefs().lineColor;;
val = PyDict_GetItemString(line, "Dash");
if (val) {
sl.Dash = PyInt_AsLong(val);
} else
sl.Dash = Qt::SolidLine;
val = PyDict_GetItemString(line, "LineEnd");
if (val) {
sl.LineEnd = PyInt_AsLong(val);
} else
sl.LineEnd = Qt::FlatCap;
val = PyDict_GetItemString(line, "LineJoin");
if (val) {
sl.LineJoin = PyInt_AsLong(val);
} else
sl.LineJoin = Qt::MiterJoin;
val = PyDict_GetItemString(line, "Shade");
if (val) {
sl.Shade = PyInt_AsLong(val);
} else
sl.Shade = ScCore->primaryMainWindow()->doc->itemToolPrefs().lineColorShade;
val = PyDict_GetItemString(line, "Width");
if (val) {
sl.Width = PyFloat_AsDouble(val);
} else
sl.Width = ScCore->primaryMainWindow()->doc->itemToolPrefs().lineWidth;
val = PyDict_GetItemString(line, "Shortcut");
if (val) {
ml.shortcut = PyString_AsString(val);
} else
ml.shortcut = "";
ml.push_back(sl);
}
if (ml.size() > 0)
ScCore->primaryMainWindow()->doc->MLineStyles[Name] = ml;
Py_RETURN_NONE;
}