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

更新於: 27-Sep-2019

149 次瀏覽

開啟職業生涯

完成課程即可獲得認證

快速入門
廣告