Py_Finalize Crashes in after PyRun_File

mk mrunalinikulkarni at yahoo.com
Fri Oct 4 09:54:26 CEST 2002


I run a python script which contains objects of classes declared in an
extension module.

the code that i use to execute the script file is as follows-

if (!Py_IsInitialized()) Py_Initialize();
				
int rc = PyRun_SimpleString("import sys, StringIO");
int rc1 = PyRun_SimpleString("sys.stderr=sys._capture=StringIO.StringIO()");
int rc2 = PyRun_SimpleString("sys.stdout=sys._capture1=StringIO.StringIO()");
			
PyObject *mDict;
mDict = PyDict_New(); 
		         
		
PyDict_SetItemString(mDict,
"__builtins__",PyEval_GetBuiltins());//init the dict with the global
variables
		
   
CString buff,buff1;
buff="import hit";
PyRun_String(buff.GetBuffer(0),file_input,mDict,mDict); 
   		
		
buff1="from hit import *";
PyRun_String(buff1.GetBuffer(0),file_input,mDict,mDict);
			
      
FILE *fp = fopen (ScriptFilePath, "r");//open the script file
     
		
if(fp)
{     
  int i=Py_file_input;     
  PyObject* pSucc=PyRun_File(fp,ScriptFilePath.GetBuffer(0),i,mDict,mDict);
				
	if(PyErr_Occurred())
	{
 	PyErr_Print();
     	      
	PyObject* sysmod = PyImport_ImportModule("sys");
	PyObject* capobj = PyObject_GetAttrString(sysmod,"_capture");
	PyObject* strres = PyObject_CallMethod(capobj,"getvalue",0);
      
	CString cresult;
	if(strres)
		cresult = PyString_AsString(strres);
      
		out->m_strErr=cresult;
					
		Py_XDECREF(sysmod);
		Py_XDECREF(capobj);
		Py_XDECREF(strres);
					
	}
										
	fclose( fp );

	Py_XDECREF(pSucc);
	Py_XDECREF(mDict);
}
	
	Py_Finalize();

This code gets executed from a menu item click of my VC++ 6.0
application. the first time i execute it the script gets executed
fine. but the second time i execute the code it crashes at PyRun_File
statement. This does not happen if i comment Py_Finalize in the above
code. Then the code can be executed repetitively without a crash.


the simple python script that i execute is as follows-

#script starts here

p=hit.printer()

if(p.start("list")):
	p.end()

#script ends here

Here hit is the name of the module that has been imported into my VC
Application which executes the script.(the first code given above)

printer is the class defined in the module. it contains a private
variable which is an object of  a class in my VC++ extension dll.

class printer  
{
public:
	//some functions defined here along with the constructor and
destructor of the printer class
				
private:
		CPrintContext m_Pc; ->c++ class in a dll
		row *pRow;
		
};
 


All the script does is instantiates a printer object and calling start
and end method on it.

any idea why PyRun_File crashes the second time i excute the script?

Thanks,
mk



More information about the Python-list mailing list