如何从 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

更新于: 2019-09-27

150 人浏览

开启你的 职业生涯

完成课程以获得认证

开始
广告
© . All rights reserved.