[C++-sig] PyErr_Print error track in c++

千里马肝 tlovexyj at 21cn.com
Thu Mar 25 02:30:58 CET 2004


hello, c++-sig at python.org

	I write own class to track PyErr_Print message for my c++ application.
	And I use PyObject_CallObject to call some function in some module.
	But, when some error in the module or the function of the module, who i use PyImport_ImportModule to import or call, it cannot report error message for me. :(

	What can be the problem ?

	below is track code:

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++ code embed 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()");
	}
}

          2004-03-24


More information about the Cplusplus-sig mailing list