簡體   English   中英

如何在 C++ 中列出 Python 模塊的所有 function 名稱?

[英]How to list all function names of a Python module in C++?

我有一個 C++ 程序,我想導入一個 Python 模塊並列出該模塊中的所有 function 名稱。 我該怎么做?

我使用以下代碼從模塊中獲取字典:

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'

筆記:

為了解決這個問題,我不得不深入研究文檔。 頁。 這些是我使用的頁面的鏈接:

很明顯,我沒有檢查NULL (或nullptr )的任何指針以保持示例簡短緊湊。 當然,生產代碼應該這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM