List all methods in COMobject

f.rodrigues picture f.rodrigues · Dec 9, 2014 · Viewed 14.2k times · Source

Is it possible?

Something in the lines of :

import win32com.client
ProgID = "someProgramID"
com_object = win32com.client.Dispatch(ProgID)

for methods in com_object:
    print methods

I got the com_object.__dict__, which lists:

[_oleobj_, _lazydata_, _olerepr_, _unicode_to_string_, _enum_, _username_, _mapCachedItems_, _builtMethods_]

Most are empty, except:

  • _oleobj_ (PyIDispatch)
  • _lazydata_ (PyITypeInfo)
  • _olerepr_ (LazyDispatchItem instance)
  • _username_ (<unknown>)

But I don't know how to access anything on those types.

Answer

z33k picture z33k · Aug 28, 2018

For those who find the accepted answer not working (I guess something changed with how pywin32 works in Python3) - there's still a way to get objects having a _prop_map_get_ attribute (a dict that holds object's fields as keys). You just have to create the main app object with win32com.client.gencache.EnsureDispatch().

Here's a convenience function I wrote that lists fields and methods of a passed COM object created that way:

from inspect import getmembers


def print_members(obj, obj_name="placeholder_name"):
    """Print members of given COM object"""
    try:
        fields = list(obj._prop_map_get_.keys())
    except AttributeError:
        print("Object has no attribute '_prop_map_get_'")
        print("Check if the initial COM object was created with"
              "'win32com.client.gencache.EnsureDispatch()'")
        raise
    methods = [m[0] for m in getmembers(obj) if (not m[0].startswith("_")
                                                 and "clsid" not in m[0].lower())]

    if len(fields) + len(methods) > 0:
        print("Members of '{}' ({}):".format(obj_name, obj))
    else:
        raise ValueError("Object has no members to print")

    print("\tFields:")
    if fields:
        for field in fields:
            print(f"\t\t{field}")
    else:
        print("\t\tObject has no fields to print")

    print("\tMethods:")
    if methods:
        for method in methods:
            print(f"\t\t{method}")
    else:
        print("\t\tObject has no methods to print")

For an Excel object created with win32com.client.gencache.EnsureDispatch("Excel.Application") its output would be:

Members of 'Excel.Application' (Microsoft Excel):
    Fields:
        ActiveCell
        ActiveChart
        ActiveDialog
        ActiveEncryptionSession
        ...
        Workbooks
        WorksheetFunction
        Worksheets
        _Default
    Methods:
        ActivateMicrosoftApp
        AddChartAutoFormat
        AddCustomList
        Calculate
        ...
        Union
        Volatile
        Wait