本文整理汇总了C++中PyErr_Fetch函数的典型用法代码示例。如果您正苦于以下问题:C++ PyErr_Fetch函数的具体用法?C++ PyErr_Fetch怎么用?C++ PyErr_Fetch使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了PyErr_Fetch函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: TRACEBACK_FETCH_ERROR
QString QgsPythonUtilsImpl::getTraceback()
{
#define TRACEBACK_FETCH_ERROR(what) {errMsg = what; goto done;}
// acquire global interpreter lock to ensure we are in a consistent state
PyGILState_STATE gstate;
gstate = PyGILState_Ensure();
QString errMsg;
QString result;
PyObject *modStringIO = NULL;
PyObject *modTB = NULL;
PyObject *obStringIO = NULL;
PyObject *obResult = NULL;
PyObject *type, *value, *traceback;
PyErr_Fetch( &type, &value, &traceback );
PyErr_NormalizeException( &type, &value, &traceback );
modStringIO = PyImport_ImportModule( "cStringIO" );
if ( modStringIO == NULL )
TRACEBACK_FETCH_ERROR( "can't import cStringIO" );
obStringIO = PyObject_CallMethod( modStringIO, ( char* ) "StringIO", NULL );
/* Construct a cStringIO object */
if ( obStringIO == NULL )
TRACEBACK_FETCH_ERROR( "cStringIO.StringIO() failed" );
modTB = PyImport_ImportModule( "traceback" );
if ( modTB == NULL )
TRACEBACK_FETCH_ERROR( "can't import traceback" );
obResult = PyObject_CallMethod( modTB, ( char* ) "print_exception",
( char* ) "OOOOO",
type, value ? value : Py_None,
traceback ? traceback : Py_None,
Py_None,
obStringIO );
if ( obResult == NULL )
TRACEBACK_FETCH_ERROR( "traceback.print_exception() failed" );
Py_DECREF( obResult );
obResult = PyObject_CallMethod( obStringIO, ( char* ) "getvalue", NULL );
if ( obResult == NULL )
TRACEBACK_FETCH_ERROR( "getvalue() failed." );
/* And it should be a string all ready to go - duplicate it. */
if ( !PyString_Check( obResult ) )
TRACEBACK_FETCH_ERROR( "getvalue() did not return a string" );
result = PyString_AsString( obResult );
done:
// All finished - first see if we encountered an error
if ( result.isEmpty() && !errMsg.isEmpty() )
{
result = errMsg;
}
Py_XDECREF( modStringIO );
Py_XDECREF( modTB );
Py_XDECREF( obStringIO );
Py_XDECREF( obResult );
Py_XDECREF( value );
Py_XDECREF( traceback );
Py_XDECREF( type );
// we are done calling python API, release global interpreter lock
PyGILState_Release( gstate );
return result;
}
示例2: PyObject_ClearWeakRefs
/* This function is called by the tp_dealloc handler to clear weak references.
*
* This iterates through the weak references for 'object' and calls callbacks
* for those references which have one. It returns when all callbacks have
* been attempted.
*/
void
PyObject_ClearWeakRefs(PyObject *object)
{
PyWeakReference **list;
if (object == NULL
|| !PyType_SUPPORTS_WEAKREFS(Py_TYPE(object))
|| object->ob_refcnt != 0) {
PyErr_BadInternalCall();
return;
}
list = GET_WEAKREFS_LISTPTR(object);
/* Remove the callback-less basic and proxy references */
if (*list != NULL && (*list)->wr_callback == NULL) {
clear_weakref(*list);
if (*list != NULL && (*list)->wr_callback == NULL)
clear_weakref(*list);
}
if (*list != NULL) {
PyWeakReference *current = *list;
Py_ssize_t count = _PyWeakref_GetWeakrefCount(current);
PyObject *err_type, *err_value, *err_tb;
PyErr_Fetch(&err_type, &err_value, &err_tb);
if (count == 1) {
PyObject *callback = current->wr_callback;
current->wr_callback = NULL;
clear_weakref(current);
if (callback != NULL) {
if (current->ob_refcnt > 0)
handle_callback(current, callback);
Py_DECREF(callback);
}
}
else {
PyObject *tuple;
Py_ssize_t i = 0;
tuple = PyTuple_New(count * 2);
if (tuple == NULL) {
_PyErr_ReplaceException(err_type, err_value, err_tb);
return;
}
for (i = 0; i < count; ++i) {
PyWeakReference *next = current->wr_next;
if (current->ob_refcnt > 0)
{
Py_INCREF(current);
PyTuple_SET_ITEM(tuple, i * 2, (PyObject *) current);
PyTuple_SET_ITEM(tuple, i * 2 + 1, current->wr_callback);
}
else {
Py_DECREF(current->wr_callback);
}
current->wr_callback = NULL;
clear_weakref(current);
current = next;
}
for (i = 0; i < count; ++i) {
PyObject *callback = PyTuple_GET_ITEM(tuple, i * 2 + 1);
/* The tuple may have slots left to NULL */
if (callback != NULL) {
PyObject *item = PyTuple_GET_ITEM(tuple, i * 2);
handle_callback((PyWeakReference *)item, callback);
}
}
Py_DECREF(tuple);
}
assert(!PyErr_Occurred());
PyErr_Restore(err_type, err_value, err_tb);
}
}
示例3: GREENLET_NOINLINE
static int GREENLET_NOINLINE(g_initialstub)(void* mark)
{
int err;
PyObject *o, *run;
PyObject *exc, *val, *tb;
PyObject *run_info;
PyGreenlet* self = ts_target;
PyObject* args = ts_passaround_args;
PyObject* kwargs = ts_passaround_kwargs;
/* save exception in case getattr clears it */
PyErr_Fetch(&exc, &val, &tb);
/* self.run is the object to call in the new greenlet */
run = PyObject_GetAttrString((PyObject*) self, "run");
if (run == NULL) {
Py_XDECREF(exc);
Py_XDECREF(val);
Py_XDECREF(tb);
return -1;
}
/* restore saved exception */
PyErr_Restore(exc, val, tb);
/* recheck the state in case getattr caused thread switches */
if (!STATE_OK) {
Py_DECREF(run);
return -1;
}
/* recheck run_info in case greenlet reparented anywhere above */
run_info = green_statedict(self);
if (run_info == NULL || run_info != ts_current->run_info) {
Py_DECREF(run);
PyErr_SetString(PyExc_GreenletError, run_info
? "cannot switch to a different thread"
: "cannot switch to a garbage collected greenlet");
return -1;
}
/* by the time we got here another start could happen elsewhere,
* that means it should now be a regular switch
*/
if (PyGreenlet_STARTED(self)) {
Py_DECREF(run);
ts_passaround_args = args;
ts_passaround_kwargs = kwargs;
return 1;
}
/* start the greenlet */
self->stack_start = NULL;
self->stack_stop = (char*) mark;
if (ts_current->stack_start == NULL) {
/* ts_current is dying */
self->stack_prev = ts_current->stack_prev;
}
else {
self->stack_prev = ts_current;
}
self->top_frame = NULL;
self->exc_type = NULL;
self->exc_value = NULL;
self->exc_traceback = NULL;
self->recursion_depth = PyThreadState_GET()->recursion_depth;
/* restore arguments in case they are clobbered */
ts_target = self;
ts_passaround_args = args;
ts_passaround_kwargs = kwargs;
/* perform the initial switch */
err = g_switchstack();
/* returns twice!
The 1st time with err=1: we are in the new greenlet
The 2nd time with err=0: back in the caller's greenlet
*/
if (err == 1) {
/* in the new greenlet */
PyGreenlet* origin;
#if GREENLET_USE_TRACING
PyObject* tracefunc;
#endif
PyObject* result;
PyGreenlet* parent;
self->stack_start = (char*) 1; /* running */
/* grab origin while we still can */
origin = ts_origin;
ts_origin = NULL;
/* now use run_info to store the statedict */
o = self->run_info;
self->run_info = green_statedict(self->parent);
Py_INCREF(self->run_info);
Py_XDECREF(o);
#if GREENLET_USE_TRACING
if ((tracefunc = PyDict_GetItem(self->run_info, ts_tracekey)) != NULL) {
Py_INCREF(tracefunc);
//.........这里部分代码省略.........
示例4: pyewf_file_object_read_buffer
/* Reads a buffer from the file object
* Make sure to hold the GIL state before calling this function
* Returns the number of bytes read if successful, or -1 on error
*/
ssize_t pyewf_file_object_read_buffer(
PyObject *file_object,
uint8_t *buffer,
size_t size,
libcerror_error_t **error )
{
PyObject *argument_size = NULL;
PyObject *exception_string = NULL;
PyObject *exception_traceback = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyObject *method_name = NULL;
PyObject *method_result = NULL;
char *error_string = NULL;
char *safe_buffer = NULL;
static char *function = "pyewf_file_object_read_buffer";
Py_ssize_t safe_read_count = 0;
ssize_t read_count = 0;
int result = 0;
if( file_object == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid file object.",
function );
return( -1 );
}
if( buffer == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid buffer.",
function );
return( -1 );
}
if( size > (size_t) SSIZE_MAX )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid size value exceeds maximum.",
function );
return( -1 );
}
if( size > 0 )
{
method_name = PyString_FromString(
"read" );
argument_size = PyLong_FromSize_t(
size );
PyErr_Clear();
method_result = PyObject_CallMethodObjArgs(
file_object,
method_name,
argument_size,
NULL );
if( PyErr_Occurred() )
{
PyErr_Fetch(
&exception_type,
&exception_value,
&exception_traceback );
exception_string = PyObject_Repr(
exception_value );
error_string = PyString_AsString(
exception_string );
if( error_string != NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
LIBCERROR_IO_ERROR_READ_FAILED,
"%s: unable to read from file object with error: %s.",
function,
error_string );
}
else
{
libcerror_error_set(
error,
//.........这里部分代码省略.........
示例5: pyewf_file_object_seek_offset
/* Seeks a certain offset within the file object
* Make sure to hold the GIL state before calling this function
* Returns 1 if successful or -1 on error
*/
int pyewf_file_object_seek_offset(
PyObject *file_object,
off64_t offset,
int whence,
libcerror_error_t **error )
{
PyObject *argument_offset = NULL;
PyObject *argument_whence = NULL;
PyObject *exception_string = NULL;
PyObject *exception_traceback = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyObject *method_name = NULL;
PyObject *method_result = NULL;
char *error_string = NULL;
static char *function = "pyewf_file_object_seek_offset";
if( file_object == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid file object.",
function );
return( -1 );
}
#if defined( HAVE_LONG_LONG )
if( offset > (off64_t) INT64_MAX )
#else
if( offset > (off64_t) LONG_MAX )
#endif
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_VALUE_EXCEEDS_MAXIMUM,
"%s: invalid offset value exceeds maximum.",
function );
return( -1 );
}
if( ( whence != SEEK_CUR )
&& ( whence != SEEK_END )
&& ( whence != SEEK_SET ) )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_UNSUPPORTED_VALUE,
"%s: unsupported whence.",
function );
return( -1 );
}
method_name = PyString_FromString(
"seek" );
#if defined( HAVE_LONG_LONG )
argument_offset = PyLong_FromLongLong(
(PY_LONG_LONG) offset );
#else
argument_offset = PyLong_FromLongLong(
(long) offset );
#endif
argument_whence = PyInt_FromLong(
(long) whence );
PyErr_Clear();
method_result = PyObject_CallMethodObjArgs(
file_object,
method_name,
argument_offset,
argument_whence,
NULL );
if( PyErr_Occurred() )
{
PyErr_Fetch(
&exception_type,
&exception_value,
&exception_traceback );
exception_string = PyObject_Repr(
exception_value );
error_string = PyString_AsString(
exception_string );
if( error_string != NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_IO,
//.........这里部分代码省略.........
示例6: Py_INCREF
// Call a single slot and return the result.
PyObject *PyQtSlot::call(PyObject *callable, PyObject *args) const
{
PyObject *sa, *oxtype, *oxvalue, *oxtb;
// Keep some compilers quiet.
oxtype = oxvalue = oxtb = 0;
// We make repeated attempts to call a slot. If we work out that it failed
// because of an immediate type error we try again with one less argument.
// We keep going until we run out of arguments to drop. This emulates the
// Qt ability of the slot to accept fewer arguments than a signal provides.
sa = args;
Py_INCREF(sa);
for (;;)
{
PyObject *nsa, *xtype, *xvalue, *xtb, *res;
if ((res = PyEval_CallObject(callable, sa)) != NULL)
{
// Remove any previous exception.
if (sa != args)
{
Py_XDECREF(oxtype);
Py_XDECREF(oxvalue);
Py_XDECREF(oxtb);
PyErr_Clear();
}
Py_DECREF(sa);
return res;
}
// Get the exception.
PyErr_Fetch(&xtype, &xvalue, &xtb);
// See if it is unacceptable. An acceptable failure is a type error
// with no traceback - so long as we can still reduce the number of
// arguments and try again.
if (!PyErr_GivenExceptionMatches(xtype, PyExc_TypeError) || xtb ||
PyTuple_Size(sa) == 0)
{
// If there is a traceback then we must have called the slot and
// the exception was later on - so report the exception as is.
if (xtb)
{
if (sa != args)
{
Py_XDECREF(oxtype);
Py_XDECREF(oxvalue);
Py_XDECREF(oxtb);
}
PyErr_Restore(xtype,xvalue,xtb);
}
else if (sa == args)
{
PyErr_Restore(xtype, xvalue, xtb);
}
else
{
// Discard the latest exception and restore the original one.
Py_XDECREF(xtype);
Py_XDECREF(xvalue);
Py_XDECREF(xtb);
PyErr_Restore(oxtype, oxvalue, oxtb);
}
break;
}
// If this is the first attempt, save the exception.
if (sa == args)
{
oxtype = xtype;
oxvalue = xvalue;
oxtb = xtb;
}
else
{
Py_XDECREF(xtype);
Py_XDECREF(xvalue);
Py_XDECREF(xtb);
}
// Create the new argument tuple.
if ((nsa = PyTuple_GetSlice(sa, 0, PyTuple_Size(sa) - 1)) == NULL)
{
// Tidy up.
Py_XDECREF(oxtype);
Py_XDECREF(oxvalue);
Py_XDECREF(oxtb);
break;
}
//.........这里部分代码省略.........
示例7: pyewf_file_object_get_offset
/* Retrieves the current offset within the file object
* Make sure to hold the GIL state before calling this function
* Returns 1 if successful or -1 on error
*/
int pyewf_file_object_get_offset(
PyObject *file_object,
off64_t *offset,
libcerror_error_t **error )
{
PyObject *exception_string = NULL;
PyObject *exception_traceback = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyObject *method_name = NULL;
PyObject *method_result = NULL;
char *error_string = NULL;
static char *function = "pyewf_file_object_get_offset";
int result = 0;
if( file_object == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid file object.",
function );
return( -1 );
}
if( offset == NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_ARGUMENTS,
LIBCERROR_ARGUMENT_ERROR_INVALID_VALUE,
"%s: invalid offset.",
function );
return( -1 );
}
method_name = PyString_FromString(
"get_offset" );
PyErr_Clear();
/* Determine if the file object has the get_offset method
*/
result = PyObject_HasAttr(
file_object,
method_name );
if( result == 0 )
{
Py_DecRef(
method_name );
/* Fall back to the tell method
*/
method_name = PyString_FromString(
"tell" );
}
PyErr_Clear();
method_result = PyObject_CallMethodObjArgs(
file_object,
method_name,
NULL );
if( PyErr_Occurred() )
{
PyErr_Fetch(
&exception_type,
&exception_value,
&exception_traceback );
exception_string = PyObject_Repr(
exception_value );
error_string = PyString_AsString(
exception_string );
if( error_string != NULL )
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_GET_FAILED,
"%s: unable to retrieve current offset in file object with error: %s.",
function,
error_string );
}
else
{
libcerror_error_set(
error,
LIBCERROR_ERROR_DOMAIN_RUNTIME,
LIBCERROR_RUNTIME_ERROR_GET_FAILED,
"%s: unable to retrieve current offset in file object.",
function );
//.........这里部分代码省略.........
示例8: profiler_callback
static int
profiler_callback(PyObject *self, PyFrameObject *frame, int what,
PyObject *arg)
{
ProfilerObject *pObj = (ProfilerObject*)self;
{
/* keep error state, see ptrace_enter_call above.
* We could keep this more focused, only really needed
* when calling a user time function, and initializing
* a user object
*/
PyObject *et, *ev, *tb;
PyErr_Fetch(&et, &ev, &tb);
pObj->currentTime = CALL_TIMER(pObj);
SelectStack(pObj);
PyErr_Restore(et, ev, tb);
}
if (pObj->currentProfilerStack == NULL)
return 0;
switch (what) {
/* the 'frame' of a called function is about to start its execution */
case PyTrace_CALL:
ptrace_enter_call(self, (void *)frame->f_code,
(PyObject *)frame->f_code);
break;
/* the 'frame' of a called function is about to finish
(either normally or with an exception) */
case PyTrace_RETURN:
ptrace_leave_call(self, (void *)frame->f_code);
break;
/* case PyTrace_EXCEPTION:
If the exception results in the function exiting, a
PyTrace_RETURN event will be generated, so we don't need to
handle it. */
#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */
/* the Python function 'frame' is issuing a call to the built-in
function 'arg' */
case PyTrace_C_CALL:
if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
&& PyCFunction_Check(arg)) {
ptrace_enter_call(self,
((PyCFunctionObject *)arg)->m_ml,
arg);
}
break;
/* the call to the built-in function 'arg' is returning into its
caller 'frame' */
case PyTrace_C_RETURN: /* ...normally */
case PyTrace_C_EXCEPTION: /* ...with an exception set */
if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
&& PyCFunction_Check(arg)) {
ptrace_leave_call(self,
((PyCFunctionObject *)arg)->m_ml);
}
break;
#endif
default:
break;
}
return 0;
}
示例9: scriptFile
bool PythonScript::execute(TWScriptAPI *tw) const
{
PyObject * tmp;
// Load the script
QFile scriptFile(m_Filename);
if (!scriptFile.open(QIODevice::ReadOnly)) {
// handle error
return false;
}
QString contents = m_Codec->toUnicode(scriptFile.readAll());
scriptFile.close();
// Python seems to require Unix style line endings
if (contents.contains("\r"))
contents.replace(QRegExp("\r\n?"), "\n");
// Create a separate sub-interpreter for this script
PyThreadState* interpreter = Py_NewInterpreter();
// Register the types
if (!registerPythonTypes(tw->GetResult())) {
Py_EndInterpreter(interpreter);
return false;
}
pyQObject *TW;
TW = (pyQObject*)QObjectToPython(tw);
if (!TW) {
tw->SetResult(tr("Could not create TW"));
Py_EndInterpreter(interpreter);
return false;
}
// Run the script
PyObject * globals, * locals;
globals = PyDict_New();
locals = PyDict_New();
// Create a dictionary of global variables
// without the __builtins__ module, nothing would work!
PyDict_SetItemString(globals, "__builtins__", PyEval_GetBuiltins());
PyDict_SetItemString(globals, "TW", (PyObject*)TW);
PyObject * ret = NULL;
if (globals && locals)
ret = PyRun_String(qPrintable(contents), Py_file_input, globals, locals);
Py_XDECREF(globals);
Py_XDECREF(locals);
Py_XDECREF(ret);
Py_XDECREF(TW);
// Check for exceptions
if (PyErr_Occurred()) {
PyObject * errType, * errValue, * errTraceback;
PyErr_Fetch(&errType, &errValue, &errTraceback);
tmp = PyObject_Str(errValue);
QString errString;
if (!asQString(tmp, errString)) {
Py_XDECREF(tmp);
tw->SetResult(tr("Unknown error"));
return false;
}
Py_XDECREF(tmp);
tw->SetResult(errString);
/////////////////////DEBUG
// This prints the python error in the usual python way to stdout
// Simply comment this block to prevent this behavior
Py_XINCREF(errType);
Py_XINCREF(errValue);
Py_XINCREF(errTraceback);
PyErr_Restore(errType, errValue, errTraceback);
PyErr_Print();
/////////////////////DEBUG
Py_XDECREF(errType);
Py_XDECREF(errValue);
Py_XDECREF(errTraceback);
Py_EndInterpreter(interpreter);
return false;
}
// Finish
Py_EndInterpreter(interpreter);
return true;
}
示例10: formatPythonException
// Format the current Python exception as a string.
// Let Python do the work for us; call traceback.format_exception()
std::string formatPythonException() {
if (!PyErr_Occurred()) {
return "<no error?>";
}
// Retrieve Python exception and "normalize" (the docs are unclear but
// they say you should do it :) )
PyObject* exceptionObj;
PyObject* valueObj;
PyObject* tracebackObj;
PyErr_Fetch(&exceptionObj, &valueObj, &tracebackObj);
DCHECK(exceptionObj);
PyErr_NormalizeException(&exceptionObj, &valueObj, &tracebackObj);
PyObjectHandle exception(exceptionObj);
PyObjectHandle value(valueObj);
PyObjectHandle traceback(tracebackObj);
// value and traceback may be null
if (!value) {
value.reset(PyObjectHandle::INCREF, Py_None);
}
if (!traceback) {
traceback.reset(PyObjectHandle::INCREF, Py_None);
}
PyObjectHandle tbModule(PyImport_ImportModule("traceback"));
if (!tbModule) {
return "<import traceback failed>";
}
PyObject* tbDict = PyModule_GetDict(tbModule.get()); // borrowed
if (!tbDict) {
return "<no dict in traceback module>";
}
// borrowed
PyObject* formatFunc = PyDict_GetItemString(tbDict, "format_exception");
if (!formatFunc) {
return "<no format_exception in traceback module>";
}
PyObjectHandle formatted(PyObject_CallFunction(
formatFunc, const_cast<char*>("OOO"), exception.get(), value.get(),
traceback.get()));
if (!formatted) {
return "<traceback.format_exception error>";
}
// format_exception returns a list of strings that should be concatenated.
// Well then, let's do that.
if (!PyList_Check(formatted.get())) {
return "<traceback.format_exception didn't return a list>";
}
std::string out;
for (Py_ssize_t i = 0; i < PyList_GET_SIZE(formatted.get()); ++i) {
PyObject* obj = PyList_GET_ITEM(formatted.get(), i); // borrowed
char* data;
Py_ssize_t len;
if (PyString_AsStringAndSize(obj, &data, &len) == -1) {
return "<traceback.format_exception member not a string>";
}
out.append(data, len);
}
return out;
}
示例11: VARARGS
/* Fetches an error
*/
void VARARGS(
pyesedb_error_fetch,
libcerror_error_t **error,
int error_domain,
int error_code,
const char *,
format_string )
{
va_list argument_list;
char error_string[ PYESEDB_ERROR_STRING_SIZE ];
PyObject *exception_traceback = NULL;
PyObject *exception_type = NULL;
PyObject *exception_value = NULL;
PyObject *string_object = NULL;
static char *function = "pyesedb_error_fetch";
char *exception_string = NULL;
size_t error_string_length = 0;
int print_count = 0;
#if PY_MAJOR_VERSION >= 3
PyObject *utf8_string_object = NULL;
#endif
if( format_string == NULL )
{
PyErr_Format(
PyExc_ValueError,
"%s: missing format string.",
function );
return;
}
VASTART(
argument_list,
const char *,
format_string );
print_count = PyOS_vsnprintf(
error_string,
PYESEDB_ERROR_STRING_SIZE,
format_string,
argument_list );
VAEND(
argument_list );
if( print_count < 0 )
{
PyErr_Format(
PyExc_ValueError,
"%s: unable to format error string.",
function );
return;
}
error_string_length = libcstring_narrow_string_length(
error_string );
if( ( error_string_length >= 1 )
&& ( error_string[ error_string_length - 1 ] == '.' ) )
{
error_string[ error_string_length - 1 ] = 0;
}
PyErr_Fetch(
&exception_type,
&exception_value,
&exception_traceback );
string_object = PyObject_Repr(
exception_value );
#if PY_MAJOR_VERSION >= 3
utf8_string_object = PyUnicode_AsUTF8String(
string_object );
if( utf8_string_object != NULL )
{
exception_string = PyBytes_AsString(
utf8_string_object );
}
#else
exception_string = PyString_AsString(
string_object );
#endif
if( exception_string != NULL )
{
libcerror_error_set(
error,
error_domain,
error_code,
"%s with error: %s.",
error_string,
exception_string );
}
else
{
//.........这里部分代码省略.........
示例12: py_varobj_iter_next
static varobj_item *
py_varobj_iter_next (struct varobj_iter *self)
{
struct py_varobj_iter *t = (struct py_varobj_iter *) self;
struct cleanup *back_to;
PyObject *item;
PyObject *py_v;
varobj_item *vitem;
const char *name = NULL;
if (!gdb_python_initialized)
return NULL;
back_to = varobj_ensure_python_env (self->var);
item = PyIter_Next (t->iter);
if (item == NULL)
{
/* Normal end of iteration. */
if (!PyErr_Occurred ())
return NULL;
/* If we got a memory error, just use the text as the item. */
if (PyErr_ExceptionMatches (gdbpy_gdb_memory_error))
{
PyObject *type, *value, *trace;
char *name_str, *value_str;
PyErr_Fetch (&type, &value, &trace);
value_str = gdbpy_exception_to_string (type, value);
Py_XDECREF (type);
Py_XDECREF (value);
Py_XDECREF (trace);
if (value_str == NULL)
{
gdbpy_print_stack ();
return NULL;
}
name_str = xstrprintf ("<error at %d>",
self->next_raw_index++);
item = Py_BuildValue ("(ss)", name_str, value_str);
xfree (name_str);
xfree (value_str);
if (item == NULL)
{
gdbpy_print_stack ();
return NULL;
}
}
else
{
/* Any other kind of error. */
gdbpy_print_stack ();
return NULL;
}
}
if (!PyArg_ParseTuple (item, "sO", &name, &py_v))
{
gdbpy_print_stack ();
error (_("Invalid item from the child list"));
}
vitem = XNEW (struct varobj_item);
vitem->value = convert_value_from_python (py_v);
if (vitem->value == NULL)
gdbpy_print_stack ();
vitem->name = xstrdup (name);
self->next_raw_index++;
do_cleanups (back_to);
return vitem;
}
示例13: __Pyx_Raise
//.........这里部分代码省略.........
goto bad;
}
#if PY_VERSION_HEX >= 0x03030000
if (cause) {
#else
if (cause && cause != Py_None) {
#endif
PyObject *fixed_cause;
if (cause == Py_None) {
// raise ... from None
fixed_cause = NULL;
} else if (PyExceptionClass_Check(cause)) {
fixed_cause = PyObject_CallObject(cause, NULL);
if (fixed_cause == NULL)
goto bad;
} else if (PyExceptionInstance_Check(cause)) {
fixed_cause = cause;
Py_INCREF(fixed_cause);
} else {
PyErr_SetString(PyExc_TypeError,
"exception causes must derive from "
"BaseException");
goto bad;
}
PyException_SetCause(value, fixed_cause);
}
PyErr_SetObject(type, value);
if (tb) {
#if CYTHON_COMPILING_IN_PYPY
PyObject *tmp_type, *tmp_value, *tmp_tb;
PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb);
Py_INCREF(tb);
PyErr_Restore(tmp_type, tmp_value, tb);
Py_XDECREF(tmp_tb);
#else
PyThreadState *tstate = PyThreadState_GET();
PyObject* tmp_tb = tstate->curexc_traceback;
if (tb != tmp_tb) {
Py_INCREF(tb);
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_tb);
}
#endif
}
bad:
Py_XDECREF(owned_instance);
return;
}
#endif
/////////////// GetException.proto ///////////////
//@substitute: naming
//@requires: PyThreadStateGet
#if CYTHON_FAST_THREAD_STATE
#define __Pyx_GetException(type, value, tb) __Pyx__GetException($local_tstate_cname, type, value, tb)
static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); /*proto*/
#else
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
#endif
/////////////// GetException ///////////////
示例14: gen_send_ex
static PyObject *
gen_send_ex(PyGenObject *gen, PyObject *arg, int exc, int closing)
{
PyThreadState *tstate = PyThreadState_GET();
PyFrameObject *f = gen->gi_frame;
PyObject *result;
if (gen->gi_running) {
char *msg = "generator already executing";
if (PyCoro_CheckExact(gen))
msg = "coroutine already executing";
PyErr_SetString(PyExc_ValueError, msg);
return NULL;
}
if (f == NULL || f->f_stacktop == NULL) {
if (PyCoro_CheckExact(gen) && !closing) {
/* `gen` is an exhausted coroutine: raise an error,
except when called from gen_close(), which should
always be a silent method. */
PyErr_SetString(
PyExc_RuntimeError,
"cannot reuse already awaited coroutine");
} else if (arg && !exc) {
/* `gen` is an exhausted generator:
only set exception if called from send(). */
PyErr_SetNone(PyExc_StopIteration);
}
return NULL;
}
if (f->f_lasti == -1) {
if (arg && arg != Py_None) {
char *msg = "can't send non-None value to a "
"just-started generator";
if (PyCoro_CheckExact(gen))
msg = "can't send non-None value to a "
"just-started coroutine";
PyErr_SetString(PyExc_TypeError, msg);
return NULL;
}
} else {
/* Push arg onto the frame's value stack */
result = arg ? arg : Py_None;
Py_INCREF(result);
*(f->f_stacktop++) = result;
}
/* Generators always return to their most recent caller, not
* necessarily their creator. */
Py_XINCREF(tstate->frame);
assert(f->f_back == NULL);
f->f_back = tstate->frame;
gen->gi_running = 1;
result = PyEval_EvalFrameEx(f, exc);
gen->gi_running = 0;
/* Don't keep the reference to f_back any longer than necessary. It
* may keep a chain of frames alive or it could create a reference
* cycle. */
assert(f->f_back == tstate->frame);
Py_CLEAR(f->f_back);
/* If the generator just returned (as opposed to yielding), signal
* that the generator is exhausted. */
if (result && f->f_stacktop == NULL) {
if (result == Py_None) {
/* Delay exception instantiation if we can */
PyErr_SetNone(PyExc_StopIteration);
} else {
PyObject *e = PyObject_CallFunctionObjArgs(
PyExc_StopIteration, result, NULL);
if (e != NULL) {
PyErr_SetObject(PyExc_StopIteration, e);
Py_DECREF(e);
}
}
Py_CLEAR(result);
}
else if (!result && PyErr_ExceptionMatches(PyExc_StopIteration)) {
/* Check for __future__ generator_stop and conditionally turn
* a leaking StopIteration into RuntimeError (with its cause
* set appropriately). */
if (((PyCodeObject *)gen->gi_code)->co_flags &
(CO_FUTURE_GENERATOR_STOP | CO_COROUTINE | CO_ITERABLE_COROUTINE))
{
PyObject *exc, *val, *val2, *tb;
char *msg = "generator raised StopIteration";
if (PyCoro_CheckExact(gen))
msg = "coroutine raised StopIteration";
PyErr_Fetch(&exc, &val, &tb);
PyErr_NormalizeException(&exc, &val, &tb);
if (tb != NULL)
PyException_SetTraceback(val, tb);
Py_DECREF(exc);
Py_XDECREF(tb);
PyErr_SetString(PyExc_RuntimeError, msg);
PyErr_Fetch(&exc, &val2, &tb);
PyErr_NormalizeException(&exc, &val2, &tb);
Py_INCREF(val);
//.........这里部分代码省略.........
示例15: _PyIOBase_finalize
int
_PyIOBase_finalize(PyObject *self)
{
PyObject *res;
PyObject *tp, *v, *tb;
int closed = 1;
int is_zombie;
/* If _PyIOBase_finalize() is called from a destructor, we need to
resurrect the object as calling close() can invoke arbitrary code. */
is_zombie = (Py_REFCNT(self) == 0);
if (is_zombie) {
++Py_REFCNT(self);
}
PyErr_Fetch(&tp, &v, &tb);
/* If `closed` doesn't exist or can't be evaluated as bool, then the
object is probably in an unusable state, so ignore. */
res = PyObject_GetAttr(self, _PyIO_str_closed);
if (res == NULL)
PyErr_Clear();
else {
closed = PyObject_IsTrue(res);
Py_DECREF(res);
if (closed == -1)
PyErr_Clear();
}
if (closed == 0) {
res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
NULL);
/* Silencing I/O errors is bad, but printing spurious tracebacks is
equally as bad, and potentially more frequent (because of
shutdown issues). */
if (res == NULL)
PyErr_Clear();
else
Py_DECREF(res);
}
PyErr_Restore(tp, v, tb);
if (is_zombie) {
if (--Py_REFCNT(self) != 0) {
/* The object lives again. The following code is taken from
slot_tp_del in typeobject.c. */
Py_ssize_t refcnt = Py_REFCNT(self);
_Py_NewReference(self);
Py_REFCNT(self) = refcnt;
/* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
* we need to undo that. */
_Py_DEC_REFTOTAL;
/* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
* chain, so no more to do there.
* If COUNT_ALLOCS, the original decref bumped tp_frees, and
* _Py_NewReference bumped tp_allocs: both of those need to be
* undone.
*/
#ifdef COUNT_ALLOCS
--Py_TYPE(self)->tp_frees;
--Py_TYPE(self)->tp_allocs;
#endif
return -1;
}
}
return 0;
}