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

2024/9/22 4:14:32

I have a C++ program, I want to import a Python module and list all function names in this module. How can I do it?

I used the following code to get the dict from a module:

PyDictObject* pDict = (PyDictObject*)PyModule_GetDict(pModule);

But how to list the functions names?

Answer

Out of curiosity, I tried to puzzle this out.

First, a minimal Python module testModule.py:

def main():print("in test.main()")def funcTest():print("in test.funcTest()")

Second, a minimal C++ sample testPyModule.cc to load and evaluate the testModule:

// standard C++ header:
#include <iostream>// Python header:
#include <Python.h>int main()
{// initialize Python interpreterPy_Initialize();// run scriptconst 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 testModulePyObject *pModuleTest = PyImport_ImportModule("testModule"); // new reference// evaluate dictionary of testModulePyObject *const pDict = PyModule_GetDict(pModuleTest); // borrowed// find functionsstd::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 interpreterPy_Finalize();
}

Output:

Functions of testModule:
function 'main'
function 'funcTest'

Notes:

To puzzle this out, I had to dig through the doc. pages. These are the links for the pages I used:

  • Importing Modules: PyImport_ImportModule
  • Module Objects: PyModule_GetDict()
  • Function Objects: PyFunction_Check()
  • Dictionary Objects: PyDict_Next()
  • Unicode Objects and Codecs: PyUnicode_AsUTF8().

It's obvious that I didn't check any pointer for NULL (or nullptr) to keep the sample short and compact. Production code should do this, of course.

https://en.xdnf.cn/q/71994.html

Related Q&A

Pandas groupby and sum total of group

I have a Pandas DataFrame with customer refund reasons. It contains these example data rows:**case_type** **claim_type** 1 service service 2 service service 3 charg…

Capture webcam video using PyQt

Given the following PyQt code, I can perfectly capture the webcams streaming video. Now, I want to modify code, so a button named capture button is added that once pressed captures the streaming video …

Plot a 3d surface from a list of lists using matplotlib

Ive searched around for a bit, and whhile I can find many useful examples of meshgrid, none shhow clearly how I can get data from my list of lists into an acceptable form for any of the varied ways Ive…

Super fast way to compare if two strings are equal

Obviously, in Python to check whether two strings are equal you can do:"hello word" == "hello world"But what if you are comparing really long strings (in excess of 1m characters)? …

Pandas DataFrames in reportlab

I have a DataFrame, and want to output it to a pdf. Im currently trying to use ReportLab for this, but it wont seem to work. I get an error here:mytable = Table(make_pivot_table(data, pivot_cols, colum…

How to open and close a website using default browser with python

Im trying to write a python script on windows platform to open a webpage(such as Google), and then, after 10 seconds, close this website. Note: Im using Windows 7, Python 2.7.10, and IE

Comparing numpy array with itself by element efficiently

I am performing a large number of these calculations:A == A[np.newaxis].Twhere A is a dense numpy array which frequently has common values.For benchmarking purposes we can use:n = 30000 A = np.random.r…

Kivy: BoxLayout vs. GridLayout

BoxLayout(orientation=vertical) vs. GridLayout(cols=1):They both do the same thing, no? Is there a reason to choose one over the other?

Flask circular dependency

I am developing a Flask application. It is still relatively small. I had only one app.py file, but because I needed to do database migrations, I divided it into 3 using this guide:https://realpython.co…

How to create tox.ini variables

Is there a way to set arbitrary variables within tox.ini?An example would be a project name that might be used in a variety of ways. With a rather complex tox.ini, I find myself copy and pasting all …