我想在 python 应用程序中嵌入 C++。我不想使用 Boost 库。
如果 C++ 函数执行断言,我想捕获它并在我的 python 应用程序中打印错误,或者获取一些详细信息,例如 python 脚本中导致错误的行号。主要的是“我想在 python 执行流程中进一步进行”
我该怎么做?我在 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 脚本中很容易启动另一个进程,检查它是否正常终止或中止,记录它,然后继续。
例如,这里有一些执行命令行 $command
的 bash 代码,将标准错误 channel 记录到日志文件中,检查返回代码(对于 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 是您要编写的其他一些子例程。
关于python - 如何在 python 运行时捕获断言(由 C++ 引起),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32462222/