如何從 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.