[C++-sig] Fw: PyErr_Print error track in c++
千里马肝
tlovexyj at 21cn.com
Wed Mar 24 10:03:28 CET 2004
python-chinese at lists.python.cn, 您好!
我在自己的C++程序中写了一个py用来打印PyErr_Print所返回的错误。
同时在python的封装类中我用PyObject_CallObject在指定的module中调用指定的函数。
但是,如果这个module或是函数中有语法错误时,该错误机制却不能正常工作,为什么?
以下是py代码:
import sys, time
from cd2 import *
# 截获错误信息
class errCatcher:
def __init__(self, filename):
self.info = ''
self.name = filename
tmp = open(filename, 'w')
tmp.close()
def write(self, stuff):
self.info += stuff
def showmsg(self):
f = open(self.name, 'a')
f.write(time.ctime())
f.write('\n--------------------------------------------------\n')
f.write(self.info)
f.write('\n\n')
f.close()
MsgBox(self.info)
self.info = ''
# 截获输出信息
class outCatcher:
def __init__(self, filename):
self.name = filename
tmp = open(filename, 'w')
tmp.close()
def write(self, stuff):
f = open(self.name, 'a')
f.write(stuff)
f.close()
sys.stderr = errCatcher('python_err.log')
sys.stdout = outCatcher('python_out.log')
以下是C++嵌入python的调用代码:
void RunFuncInModule(const Char *szFuncName, const Char *szModuleName)
{
try
{
python::handle<> main_module( python::borrowed( PyImport_AddModule( "__main__" ) ) );
python::handle<> main_namespace( python::borrowed( PyModule_GetDict( main_module.get() ) ) );
python::handle<> local_module( python::borrowed( PyImport_ImportModule( const_cast<Char *>( szModuleName ) ) ) );
#ifdef _DEBUG
python::handle<> ( python::borrowed( PyImport_ReloadModule( local_module.get() ) ) );
#endif
python::handle<> local_namespace( python::borrowed( PyModule_GetDict( local_module.get() ) ) );
PyObject *func = python::expect_non_null( PyDict_GetItemString( local_namespace.get(), const_cast<Char *>( szFuncName ) ) );
if ( PyCallable_Check( func ) != 0 )
{
python::handle<>( PyObject_CallObject( func, NULL ) );
}
}
catch (python::error_already_set)
{
python::handle_exception();
PyErr_Print();
PyRun_SimpleString("sys.stderr.showmsg()");
}
}
致
礼!
千里马肝
tlovexyj at 21cn.com
2004-03-24
More information about the Cplusplus-sig
mailing list