[MAYA] Calling Python from C++ using MGlobal::executePythonCommand

I am having trouble capturing the return value of a Python Script called from a C++ Plugin.

I am trying to capture a MStringArray from the Python Script, but I only get an empty value. The Python is running and completing - however the result is still MStatus.kFailure - which explains why the return value is not getting sent back to C++…

I know the python script is running all the way up to the return statement because of the print statements, but for some reason, Maya thinks the Python Command failed.

edit: seems like i am not the only one to hit this problem - here is the same question dating back to 2009…
https://www.creativecrash.com/forums/api/topics/mglobal-executepythoncommand

My co-worker found the answer buried in one of the examples provided in the SDK.

in assemblyReferenceInitialRep.cpp there is an example of how to execute python code from C++ and get back a return value - lines 101-117


        MStringArray stringArrayResult;

	// Invoke: assemblyReferenceInitialRep.getInitialRep(targetAssemblyName)

	// Note: to get string result from python, it must execute a single command,
	// so wrap it in a proc

	MString pyCmd1;
	pyCmd1 = "def tempGetInitialRepProc():
";
	pyCmd1 += "	" + pyPreamble1;
	pyCmd1 += "	" + pyPreamble2;
	pyCmd1 += "	return ir.getInitialRep(\'";
	pyCmd1 += aFn.name();
	pyCmd1 += "\')
";
	MGlobal::executePythonCommand(pyCmd1);

	MString pyCmd2;
	pyCmd2 = "tempGetInitialRepProc()";
	MGlobal::executePythonCommand(pyCmd2, stringArrayResult);

I assume this stuff is executed in the global scope? IE tempGetInitialRepProc() would be defined for general usage in a Python command window after this executes?

I don’t think it is, i think its just for use while the plugin is doing its thing, although i did not try to execute the temp function…