如何正确使用Python的capi和异常?

2024-09-28 22:19:53 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我做一些像

 >>> x = int(1,2,3,4,5)

我立即得到一个致命的错误(如果程序是在一个预先编写的脚本中,它将结束程序的执行)

^{pr2}$

并且x未定义:

 >>> x
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 NameError: name 'x' is not defined

如何在Python的capi中实现它呢?我找到了一些documentation,但我不确定我是否知道如何正确使用它。在

我一直在努力:

  1. 打印:

    if(something) {
        PyErr_SetString(PyExc_TypeError, "Oh no!");
        PyErr_Print();
    }
    

    不幸的是,这只打印出异常,程序继续运行。另外,-如果我理解正确-PyErr_Print()会从某种队列中删除异常,这样Python就认为它已经被处理了。它看起来是这样的:

    >>> import awesomemod
    >>> x = awesomemod.thing()
    TypeError: Oh no!
    >>> x # x is defined because the function returns None eventually
    >>> 
    
  2. PyErr_Occurred()

    if(something) {
        PyErr_SetString(PyExc_TypeError, "Oh no!");
        PyErr_Occurred();
    }
    

    行为:

    >>> import awesomemod
    >>> awesomemod.thing()
    >>>
    TypeError: Oh no!
    >>>
    

    所以有点晚了。。。

  3. return PyErr_Occurred()

    if(something) {
        PyErr_SetString(PyExc_TypeError, "Oh no!");
        return PyErr_Occurred();
    }
    

    行为:

    >>> import awesomemod
    >>> awesomemod.thing()
    <type 'exceptions.TypeError'>
    >>>
    TypeError: Oh no!
    

    这个真的很奇怪。

我需要做什么来获得内置函数的行为?在

编辑:我尝试了@user2864740在评论中提出的建议,效果非常好!在

 if(something) {
     PyErr_SetString(PyExc_TypeError, "Oh no!");
     return (PyObject *) NULL;
 }

Tags: noimport程序returnifissomethingoh
2条回答

通过设置异常对象或字符串,然后从函数返回NULL,在C中引发异常。在

作为Ignacio Vazquez-Abrams said

Raising an exception in C is done by setting the exception object or string and then returning NULL from the function.

对于常见的异常类型,有一些方便的函数可以很容易地做到这一点。例如,^{}可以这样使用:

PyObject *my_function(void)
{
    return PyErr_NoMemory();  // Sets the exception and returns NULL
}

相关问题 更多 >