从 Python C API 中的字符串导入模块

2023-12-28

使用 Python C API 从文件导入 Python 模块相对容易PyImport_Import()但是我需要使用存储在字符串中的函数。有没有办法从字符串导入 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和Python代码MyModuleCode你就完成了!

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

从 Python C API 中的字符串导入模块 的相关文章

随机推荐