python - 如何在 C++ 中列出 Python 模块的所有函数名称?

标签 python c++ python-c-api

我有一个 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'

注意事项:

为了解决这个问题,我不得不仔细阅读文档。页。这些是我使用的页面的链接:

很明显,我没有检查任何指向 NULL(或 nullptr)的指针以保持示例简短紧凑。当然,生产代码应该这样做。

关于python - 如何在 C++ 中列出 Python 模块的所有函数名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58075398/

相关文章:

c++ - 非常简单的程序通过了 VS2010 c++ 内存泄漏检查器,但在销毁所有对象后在程序结束时仍然使用更多内存?

c++ - 如何根据参数化类型的特定成员的类型对模板类函数进行不同的实现

android - 如何使用 QAndroidJniObject 从 Qt 内部调用 Java 代码?

python - 从 Python C 扩展函数返回参数时需要 INCREF?

python - 尝试对用户输入数据进行标签编码时出现类型错误

python - 在 python 中的第 n 个字节之后追加到文件

python - 如何对 DataFrame 中的数值和字符串值进行排序?

python-3.x - 使用来自 Python 3.8.1 C API 的 format_exc 返回 NoneType

multithreading - 如何同时在两个不同的线程中执行 PyObject_CallObject()?

python - 链接到 Flask 模板中的特定位置