better way of executing expression/statement in C?

David Faden dfaden at iastate.edu
Thu May 20 13:55:20 EDT 2004


Hi,

Given arbitrary Python source code input by the user, I want to get the 
result of executing that source as an expression if it is an expression 
and otherwise execute the source as a statement. Currently, I'm 
accomplishing this as follows (in a category on NSString), but it seems 
kludgy to rely on detecting a syntax error.

- (PyObject*)executePythonSourceWithGlobals:(PyObject*)globals
{
	const char* source = [self UTF8String];
	PyObject* result = PyRun_String(source, Py_eval_input, globals, 
globals);
	if (!result && PyErr_ExceptionMatches(PyExc_SyntaxError)) {
		PyErr_Clear();
		result = PyRun_String(source, Py_file_input, globals, globals);
	}
	return result;
}

How would you accomplish this? How does the interpreter do it?

Thank you.

David
AIM: pitulx





More information about the Python-list mailing list