Embedding python, run a function and get it's result

Charles Heizer ceh329 at gmail.com
Tue Jan 31 17:11:10 EST 2017

I'm messing around with the embedded python and I can get parts to work. What I'm having a hard time is getting my head around calling a function in the python string and getting it's result.

Question, how do I load the python script and call runMe() and get it's value?


Example Works

Obj-C Code:

PyObject *py_main, *py_dict;
py_main = PyImport_AddModule("__main__");
py_dict = PyModule_GetDict(py_main);
// Run the python source code
PyRun_String([auditScript UTF8String], Py_file_input, py_dict, py_dict);

PyObject *pythonString = PyDict_GetItemString(py_dict, "x") ;
if (!pythonString) {
        NSLog(@"pythonString returned NULL");
        return "NO";

// Convert the unpickled Python string to a C string
char *cString = PyString_AsString(pythonString);
f (!cString) {
    NSLog(@"Failed converting pythonString string to C string");
    return 1;
NSLog(@"answer: %@",[NSString cString]);

Python Code:

x = "NA"
def runMe():
	return "YES"

x = runMe()

More information about the Python-list mailing list