简体   繁体   English

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

[英]How to catch assertion(caused in C++) during runtime in python

I want to embed C++ in python application. 我想在python应用程序中嵌入C ++。 I don't want to use Boost library. 我不想使用Boost库。

If C++ function do assertion, I want to catch it and print error in my python application or get some detailed information like line number in python script that caused error. 如果C ++函数做断言,我想抓住它并在我的python应用程序中打印错误或获取一些详细信息,如python脚本中的行号导致错误。 and main thing is "I want to proceed further in python execution flow" 主要是“我想进一步在python执行流程中”

How can I do it? 我该怎么做? I can't find any functions to get detailed assertion information in Python API or C++. 我找不到任何函数来获取Python API或C ++中的详细断言信息。

C++ Code C ++代码

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

Python Code 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'

Thanks in advance. 提前致谢。

This can't really be done in exactly the way you say, (as was also pointed out in the comments). 这不可能完全按照你说的方式完成(正如评论中也指出的那样)。

Once the assertion happens and SIGABRT is sent to the process, it's in the operating system's hands what will happen, and generally the process will be killed. 一旦断言发生并且SIGABRT被发送到进程,它将在操作系统的手中发生什么,并且通常该进程将被终止。

The simplest way to recover from a process being killed, is to have the process launched by an external process. 从被杀死的进程中恢复的最简单方法是让进程由外部进程启动。 Like, a secondary python script, or a shell script. 比如,辅助python脚本或shell脚本。 It's easy in bash scripting, for instance, to launch another process, check if it terminates normally or is aborted, log it, and continue. 例如,在bash脚本中很容易启动另一个进程,检查它是否正常终止或中止,记录并继续。

For instance here's some bash code that executes command line $command , logs the standard error channel to a log file, checks the return code (which will be 130 or something for an SIGABRT) and does something in the various cases: 例如,这里有一些执行命令行$command bash代码,将标准错误通道记录到日志文件中,检查返回代码(对于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

Where check_errs is some other subroutine that you would write. check_errs是你要编写的其他子例程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM