c++内嵌python脚本,boost::python::error_already_set

yusui09 2011-12-27 04:35:51
话不多说代码直接贴上
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++程序宕掉。有哪位混合编程高手讲解下。


...全文
481 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
angel_su 2011-12-30
  • 打赏
  • 举报
回复
我简单试了下正常,你最好上个代码来瞧瞧...
yusui09 2011-12-28
  • 打赏
  • 举报
回复
不行啊, 还是会崩溃,提示已放弃, 如何能不要让程序挂掉呢。
angel_su 2011-12-28
  • 打赏
  • 举报
回复
默认没有getvalue函数吧?貌似先用StringIO转向输出再执行你的脚本,类似:

python::exec("import cStringIO\n"
"import sys\n"
"sys.stderr = cStringIO.StringIO()",
main_namespace);
iambic 2011-12-27
  • 打赏
  • 举报
回复
try...catch啊。

37,722

社区成员

发帖
与我相关
我的任务
社区描述
JavaScript,VBScript,AngleScript,ActionScript,Shell,Perl,Ruby,Lua,Tcl,Scala,MaxScript 等脚本语言交流。
社区管理员
  • 脚本语言(Perl/Python)社区
  • IT.BOB
加入社区
  • 近7日
  • 近30日
  • 至今

试试用AI创作助手写篇文章吧