使用带有 PyImport_Import()
的 Python C API 从文件导入 Python 模块相对容易,但是我需要使用存储在字符串中的函数。有没有办法从字符串中导入 python 模块(澄清一下:没有文件;代码在字符串中)或者我必须将字符串保存为临时文件吗?
最佳答案
无需使用临时文件。使用此代码:
const char *MyModuleName = "blah";
const char *MyModuleCode = "print 'Hello world!'";
PyObject *pyModule = PyModule_New(MyModuleName);
// Set properties on the new module object
PyModule_AddStringConstant(pyModule, "__file__", "");
PyObject *localDict = PyModule_GetDict(pyModule); // Returns a borrowed reference: no need to Py_DECREF() it once we are done
PyObject *builtins = PyEval_GetBuiltins(); // Returns a borrowed reference: no need to Py_DECREF() it once we are done
PyDict_SetItemString(localDict, "__builtins__", builtins);
// Define code in the newly created module
PyObject *pyValue = PyRun_String(MyModuleCode, Py_file_input, localDict, localDict);
if (pyValue == NULL) {
// Handle error
}
else
Py_DECREF(pyValue);
这是取自真实商业应用程序的代码(我通过删除错误处理和其他不需要的细节对其进行了轻微修改)。
只需在 MyModuleName
中设置所需的模块名称,在 MyModuleCode
中设置 Python 代码即可!
关于python - 从 Python C API 中的字符串导入模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39808521/