python如何让程序中断,如何从Python C代码中断言?

I'm writing a Python class in C and I want to put assertions in my debug code. assert.h suits me fine. This only gets put in debug compiles so there's no chance of an assert failure impacting a user of the Python code*.

I'm trying to divide my 'library' code (which should be separate to the code linked against Python) so I can use it from other C code. My Python methods are therefore thinnish wrappers around my pure-C code.

So I can't do this in my 'library' code:

if (black == white)

{

PyErr_SetString(PyExc_RuntimeError, "Remap failed");

}

because this pollutes my pure-C code with Python. It's also far uglier than a simple

assert(black != white);

I believe that the Distutils compiler always sets NDEBUG, which means I can't use assert.h even in debug builds.

Mac OS and Linux.

Help!

*one argument I've heard against asserting in C code called from Python.

解决方案

Just use assert.h. It's a myth that distutils always defines NDEBUG; it only does so for Microsoft's msvc on Windows, and then only when invoked from a Python release build (not from a Python debug build).

To then define NDEBUG in your own release builds, pass a -D command line option to setup.py build_ext.

Edit: It seems that NDEBUG is defined by default through Python's Makefile's OPT setting. To reset this, run

OPT="-g -O3" python setup.py build

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值