c++内嵌python脚本,boost::python::error_already_set
话不多说代码直接贴上
int main()
{
Py_Initialize();
//引入__main__ 作用域
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
try
{
std::cout<<"will -1 end"<<std::endl;
object simple = exec_file("simple.py",main_namespace, main_namespace);
std::cout<<"will 0 end"<<std::endl;
object serverInfo = main_namespace["serverInfo"];
std::cout<<"will 1 end"<<std::endl;
std::string ipStr = extract<std::string>(serverInfo("Server","ip"));
std::cout<<"will 2 end"<<std::endl;
std::cout << "Python get ip: " << ipStr <<std::endl;
}
catch (boost::python::error_already_set)
{
PyErr_Print();
boost::python::object sys(
boost::python::handle<>(PyImport_ImportModule("sys"))
);
boost::python::object err = sys.attr("stderr");
std::string err_text = boost::python::extract<std::string>(err.attr("getvalue")());
}
return 0;
}
如果simple.py脚本内有语法错误的话, 会抛出异常, 异常信息打印出来了。但是程序是会崩溃(terminate called after throwing an instance of 'boost::python::error_already_set', 已放弃), 如何让程序不崩溃呢?就是说脚本有错误时不要让c++程序宕掉。有哪位混合编程高手讲解下。
int main()
{
Py_Initialize();
//引入__main__ 作用域
object main_module = import("__main__");
object main_namespace = main_module.attr("__dict__");
try
{
std::cout<<"will -1 end"<<std::endl;
object simple = exec_file("simple.py",main_namespace, main_namespace);
std::cout<<"will 0 end"<<std::endl;
object serverInfo = main_namespace["serverInfo"];
std::cout<<"will 1 end"<<std::endl;
std::string ipStr = extract<std::string>(serverInfo("Server","ip"));
std::cout<<"will 2 end"<<std::endl;
std::cout << "Python get ip: " << ipStr <<std::endl;
}
catch (boost::python::error_already_set)
{
PyErr_Print();
boost::python::object sys(
boost::python::handle<>(PyImport_ImportModule("sys"))
);
boost::python::object err = sys.attr("stderr");
std::string err_text = boost::python::extract<std::string>(err.attr("getvalue")());
}
return 0;
}
如果simple.py脚本内有语法错误的话, 会抛出异常, 异常信息打印出来了。但是程序是会崩溃(terminate called after throwing an instance of 'boost::python::error_already_set', 已放弃), 如何让程序不崩溃呢?就是说脚本有错误时不要让c++程序宕掉。有哪位混合编程高手讲解下。
...全文
相关推荐
Python socket.error: [Errno 98] Address already in use的原因和解决方法
在Python网络编程中,当你遇到`socket.error: [Errno 98] Address already in use`这个错误时,意味着你尝试绑定的IP地址和端口号正在被其他进程占用。这
解决python脚本中error: unrecognized arguments: True错误
在Python编程中,`error: unrecognized arguments: True` 错误通常出现在命令行解析时,当你尝试传递一个未被脚本预期的参数时。
pip 安装报错 error: Microsoft Visual C++ 14.0 is required. Get it with “Microsoft Visual C++ Build Tools
"在Windows系统上使用pip安装Python包时,可能会遇到一个常见的错误提示:error: Microsoft Visual C++ 14.0 is required. Get it wit
find_error:该脚本的目的是通过输入然后在输出中搜索日志文件
本文将深入探讨一个名为"find_error"的Python脚本,它专为在日志文件中查找错误而设计。
python解决方案:WindowsError: [Error 2]
### Python解决方案:WindowsError: [Error 2]在使用Python进行文件操作时,经常会遇到一些错误,特别是当涉及到文件系统时。


