我有一个 C++ 程序,我想导入一个 Python 模块并列出该模块中的所有函数名称。我该怎么做?
我使用以下代码从模块中获取字典:
PyDictObject* pDict = (PyDictObject*)PyModule_GetDict(pModule);
但是如何列出函数名称呢?
最佳答案
出于好奇,我试图弄清楚这一点。
首先,一个最小的 Python 模块 testModule.py
:
def main():
print("in test.main()")
def funcTest():
print("in test.funcTest()")
其次,用于加载和评估 testModule
的最小 C++ 示例 testPyModule.cc
:
// 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();
}
输出:
Functions of testModule:
function 'main'
function 'funcTest'
注意事项:
为了解决这个问题,我不得不仔细阅读文档。页。这些是我使用的页面的链接:
- Importing Modules :
PyImport_ImportModule
- Module Objects :
PyModule_GetDict()
- Function Objects :
PyFunction_Check()
- Dictionary Objects :
PyDict_Next()
- Unicode Objects and Codecs :
PyUnicode_AsUTF8()
。
很明显,我没有检查任何指向 NULL
(或 nullptr
)的指针以保持示例简短紧凑。当然,生产代码应该这样做。
关于python - 如何在 C++ 中列出 Python 模块的所有函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58075398/