我有一个 C++ 程序,我想导入一个 Python 模块并列出该模块中的所有函数名称。我该怎么做?
我使用以下代码从模块中获取字典:
PyDictObject* pDict = (PyDictObject*)PyModule_GetDict(pModule);
但如何列出函数名称呢?
出于好奇,我试图解开这个谜题。
首先,一个最小的Python模块testModule.py
:
def main():
print("in test.main()")
def funcTest():
print("in test.funcTest()")
其次,一个最小的 C++ 示例testPyModule.cc
加载并评估testModule
:
// standard C++ header:
#include <iostream>
// Python header:
#include <Python.h>
int main()
{
// initialize Python interpreter
Py_Initialize();
// run script
const char *const script =
"# tweak sys path to make Python module of cwd locatable\n"
"import sys\n"
"sys.path.insert(0, \".\")\n";
PyRun_SimpleString(script);
// get module testModule
PyObject *pModuleTest = PyImport_ImportModule("testModule"); // new reference
// evaluate dictionary of testModule
PyObject *const pDict = PyModule_GetDict(pModuleTest); // borrowed
// find functions
std::cout << "Functions of testModule:\n";
PyObject *pKey = nullptr, *pValue = nullptr;
for (Py_ssize_t i = 0; PyDict_Next(pDict, &i, &pKey, &pValue);) {
const char *key = PyUnicode_AsUTF8(pKey);
if (PyFunction_Check(pValue)) {
std::cout << "function '" << key << "'\n";
}
}
Py_DECREF(pModuleTest);
// finalize Python interpreter
Py_Finalize();
}
Output:
Functions of testModule:
function 'main'
function 'funcTest'
Notes:
为了解决这个问题,我不得不深入研究文档。页。这些是我使用的页面的链接:
-
导入模块 https://docs.python.org/3/c-api/import.html:
PyImport_ImportModule
-
模块对象 https://docs.python.org/3/c-api/module.html:
PyModule_GetDict()
-
函数对象 https://docs.python.org/3/c-api/function.html:
PyFunction_Check()
-
字典对象 https://docs.python.org/3/c-api/dict.html:
PyDict_Next()
-
Unicode 对象和编解码器 https://docs.python.org/3/c-api/unicode.html:
PyUnicode_AsUTF8()
.
很明显我没有检查任何指针NULL
(or nullptr
)以保持样本简短紧凑。当然,生产代码应该执行此操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)