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

5 c++ python windows ctypes assertions

我想在python应用程序中嵌入C++.我不想使用Boost库.

如果C++函数做断言,我想抓住它并在我的python应用程序中打印错误或获取一些详细信息,如python脚本中的行号导致错误.主要是"我想进一步在python执行流程中"

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

C++代码

void sum(int iA, int iB)
{
    assert(iA + iB >10);
}
Run Code Online (Sandbox Code Playgroud)

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'
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Chr*_*eck 0

这实际上不能完全按照您所说的方式完成(正如评论中也指出的那样)。

一旦断言发生并且 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
Run Code Online (Sandbox Code Playgroud)

其中 check_errs 是您要编写的其他子例程。