[C++-sig] Under what conditions would PyRun_SimpleFile return false?

Blake Skinner 5p4ced0ut at gmail.com
Thu Aug 17 06:26:38 CEST 2006


PyRun_SimpleFile() doesn't seem to like me.  First, passing a FILE* created by
fopen() in Visual Studio 2005 caused a runtime error, but I found a work around:

FILE* fp = PyFile_AsFile( PyFile_FromString(filename, "r") );
PyRun_SimpleString(fp, filename);

I'm mentioning this so you understand why I'm doing it in my code.

This worked fine, until I tried to construct a class around boost python, here's
the jist of it:

// constructor, Initializes python, creates the main module and gets the
// dictionary
pyEngine::pyEngine()
{
	Py_Initialize();

	// main module and main dictionary
	object main((
		handle<>(borrowed(PyImport_AddModule("__main__")))
		));
	_main = main;
	_mdict = _main.attr("__dict__");
}

// destructor
// finalizes python
pyEngine::~pyEngine()
{
	Py_Finalize();
}

//////////////////////////////////////////////////////////////////
// methods

// load a python module with the given filename
bool pyEngine::LoadModule(char *filename)
{
// originally more condensed, the 'if's were added for debugging
	PyObject *py_file = PyFile_FromString(filename, "r");
	if (!py_file)
	{
		fprintf(stderr, "Unable to locate module (pyEngine)\n");
		return false;
	}

	FILE *fp = PyFile_AsFile( py_file );
	if (!fp)
	{
		fprintf(stderr, "PyFile_AsFile returned NULL\n");
		return false;
	}

	if (!(PyRun_SimpleFile(fp, filename) == 1))
	{
		fprintf(stderr, "PyRun_SimpleFile returned 0\n");

		return false;
	}

	return true;
}

///////////////////////////////////////////////////////////////////////////////

>From stderr I found that PyRun_SimpleFile was returning 0.  I checked the
documentation and it didn't mention what conditions that would happen for.  I'll
keep looking for it on my own and post if I solve it, but any help would be
appreciated.

Thanks.




More information about the Cplusplus-sig mailing list