如何从C扩展中引发Python异常?
对于上述模块,我们需要准备以下setup.py脚本−
from distutils.core import setup, Extension
setup(name='helloworld', version='1.0', \
ext_modules=[Extension('helloworld', ['hello.c'])])
现在,我们使用以下命令,
$ python setup.py install
一旦我们安装了扩展,我们就可以在我们的Python脚本test.py中导入和调用该扩展,并在其中捕获异常,如下所示−
#test.py
import helloworld
try:
print helloworld.helloworld()
except Exception as e:
print str(e)
这将产生以下结果−
bad format char passed to Py_BuildValue
阅读更多:Python 教程