我正在尝试捕获c ++程序内部发生的异常,该异常是我使用subprocess.checkout()命令从python脚本调用的,但是它似乎没有按我的预期工作。尽管捕获到异常,但是它没有有关异常原因的必要信息。我想打印出在c ++级别发生的异常跟踪(在以下情况下为floatpointexception或除以零错误)。我是python的新手,在这方面的任何帮助都非常有用。谢谢。

以下是我用来调试此问题的示例程序。

TestCexception.cc

#include<iostream>
#include<exception>
#include <stdexcept>

using namespace std;
int main()
{
    int a=5;
    int b=0;
            try
            {   cout<< "I am a statement before division"<< endl;
                int c = a/b;
                cout<< "I am a statement after division"<< endl;
            }
            catch(exception &e)
            {
                cerr << "Cerr - To test exception \n" << endl;
            }

    return 0;
}


TestPython.py

import os
import socket
import subprocess
import sys
import traceback

print('Sample Python to simualte exception')
TestOP = 'Default'

try:
    TestOP = subprocess.check_output(["/lhome/workspace/testException/testxptn"])
except subprocess.CalledProcessError as e :
    tb = traceback.format_exc()
    print(e)
    print(tb)
    print(e.output)


电流输出:

Sample Python to simualte exception
I am a statement before division
Traceback (most recent call last):
  File "TestPython.py", line 14, in <module>
    TestOP = subprocess.check_output(["/lhome/workspace/testException/testxptn"])
  File "/usr/lib/python2.7/subprocess.py", line 223, in check_output
    raise CalledProcessError(retcode, cmd, output=output)
CalledProcessError: Command '['/lhome/workspace/testException/testxptn']' returned non-zero exit status -8


我想看的输出或类似的东西

Sample Python to simualte exception
I am a statement before division
Floating point exception
Cerr - To test exception

最佳答案

我正在尝试捕获c ++内发生的异常


整数除以零不会生成C ++异常。在Linux上,它会发出SIGFPE信号。

python3格式subprocess.CalledProcessError异常更好:

Command '['/lhome/workspace/testException/testxptn']' died with <Signals.SIGFPE: 8>.


在python2中,您可以执行以下操作:

signo_to_string = dict((getattr(signal, s), s) for s in dir(signal) if s.startswith("SIG") and not s.startswith("SIG_"))

except subprocess.CalledProcessError as e:
    print(e)
    if os.WIFSIGNALED(e.returncode):
        print("Terminated by %s.\n" % signo_to_string[abs(e.returncode)])

关于python - 如何捕获在使用python subprocess.checkout()调用的C++程序中发生的异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59103456/

10-09 19:53
查看更多