我正在尝试捕获c ++程序内部发生的异常,该异常是我使用subprocess.checkout()命令从python脚本调用的,但是它似乎并没有达到我的预期。尽管捕获到异常,但是它没有有关异常原因的必要信息。我想打印出在c ++级别发生的异常跟踪(在以下情况下为floatpointexception或除以零错误)。我是python的新手,在这方面的任何帮助都非常有用。谢谢。
下面是用于调试此问题的示例程序。
#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;
}
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)])