如果我做一些像
>>> 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,但我不确定我是否知道如何正确使用它。在
我一直在努力:
打印:
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
>>>
PyErr_Occurred()
:
if(something) {
PyErr_SetString(PyExc_TypeError, "Oh no!");
PyErr_Occurred();
}
行为:
>>> import awesomemod
>>> awesomemod.thing()
>>>
TypeError: Oh no!
>>>
所以有点晚了。。。
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;
}
通过设置异常对象或字符串,然后从函数返回
NULL
,在C中引发异常。在作为Ignacio Vazquez-Abrams said:
对于常见的异常类型,有一些方便的函数可以很容易地做到这一点。例如,^{} 可以这样使用:
相关问题 更多 >
编程相关推荐