PyObject* PythonObjIntegration::ExecuteScript(const char* moduleName, const char* functionName, PyObject* args) {
	auto module = PyImport_ImportModule(moduleName); // New ref
	if (!module) {
	/*auto locals = PyDict_New();
	auto module = PyImport_ImportModuleEx(const_cast<char*>(moduleName), MainModuleDict, locals, 0); // New ref
	Py_DECREF(locals);
	if (!module) {		*/
		logger->error("Unable to find Python module {}", moduleName);
		Py_RETURN_NONE;
	}

	auto dict = PyModule_GetDict(module); // Borrowed ref
	AddGlobalsOnDemand(dict);

	auto callback = PyDict_GetItemString(dict, functionName); // Borrowed ref

	if (!callback || !PyCallable_Check(callback)) {
		logger->error("Python module {} is missing callback {}.", moduleName, functionName);
		Py_DECREF(module);
		Py_RETURN_NONE;
	}

	auto result = PyObject_CallObject(callback, args);

	if (!result) {
		PyErr_Print();
		logger->error("Failed to invoke function {} in Python module {}.", functionName, moduleName);
		Py_DECREF(module);
		Py_RETURN_NONE;
	}

	Py_DECREF(module);
	return result;
}
Example #2
0
bool PythonIntegration::LoadScript(int scriptId, ScriptRecord &scriptOut) {
	auto it = mScripts.find(scriptId);
	if (it == mScripts.end()) {
		logger->error("Trying to invoke unknown script id {}", scriptId);
		return false;
	}

	auto &script = it->second;
	if (script.loadingError) {
		return false; // cannot execute a script we previously failed to load
	}

	// We have not yet loaded the Python module
	if (!script.module) {
		script.module = PyImport_ImportModule(script.moduleName.c_str());
		if (!script.module) {
			// Loading error
			logger->error("Could not load script {}.", script.filename);
			PyErr_Print();
			script.loadingError = true; // Do not try this over and over again
			return false;
		} else {
			// Add globals on demand
			auto dict = PyModule_GetDict(script.module);
			AddGlobalsOnDemand(dict);
		}
	}

	scriptOut = script;
	return true;
}