如何在python中运行时捕获断言(在C ++中导致)

我想在Python应用程序中embeddedC ++。 我不想使用Boost库。

如果C ++函数做断言,我想抓住它,并在我的Python应用程序中打印错误,或得到一些像python脚本中的行号,导致错误的详细信息。 主要的是“我想进一步在Python执行stream程”

我该怎么做? 我找不到任何函数来获取Python API或C ++中的详细断言信息。

C ++代码

void sum(int iA, int iB) { assert(iA + iB >10); } 

Python代码

 from ctypes import * mydll = WinDLL("C:\\Users\\cppwrapper.dll") try: mydll.sum(10,3) catch: print "exception occurred" # control should go to user whether exceptions occurs, after exception occurs if he provide yes then continue with below or else abort execution, I need help in this part as well import re for test_string in ['555-1212', 'ILL-EGAL']: if re.match(r'^\d{3}-\d{4}$', test_string): print test_string, 'is a valid US local phone number' else: print test_string, 'rejected' 

提前致谢。

这不能完全按照你说的方式来完成,(正如在评论中也指出的那样)。

一旦断言发生,SIGABRT被发送到进程,它将在操作系统的手中发生,通常这个进程将被终止。

从被杀死的进程中恢复的最简单的方法是让进程由外部进程启动。 就像一个辅助python脚本或一个shell脚本。 例如,在bash脚本中很容易启动另一个进程,检查它是否正常终止或中止,记录并继续。

例如,这里有一些bash代码执行命令行$command ,将标准错误通道记录到日志文件中,检查返回代码(对于SIGABRT,这将是130)或者在各种情况下执行某些操作:

  $command 2> error.log error_code="$?" if check_errs $error_code; then # Do something... return 0 else # Do something else... return 1 fi 

check_errs是你要编写的其他子程序。