Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Cách raise Python exception từ C extension?

Cho module trên, chúng ta cần chuẩn bị script setup.py sau:

from distutils.core import setup, Extension
setup(name='helloworld', version='1.0',
      ext_modules=[Extension('helloworld', ['hello.c'])])

Bây giờ, chúng ta dùng lệnh sau:

$ python setup.py install

Sau khi cài extension, chúng ta có thể import và call extension đó trong Python script test.py và catch exception trong nó như sau:

# test.py
import helloworld
try:
    print(helloworld.helloworld())
except Exception as e:
    print(str(e))

Điều này sẽ cho kết quả sau:

bad format char passed to Py_BuildValue