List all methods in COMobject

17,966

Solution 1

Just found how to get most of the methods:

Here's how:

import win32com.client
import pythoncom

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

for key in dir(com_object):
    method = getattr(com_object,key)
    if str(type(method)) == "<type 'instance'>":
        print key
        for sub_method in dir(method):
            if not sub_method.startswith("_") and not "clsid" in sub_method.lower():
                print "\t"+sub_method
    else:
        print "\t",method

Here's a exemple output with ProgID = "Foobar2000.Application.0.7"

Output:

Playlists
    Add
    GetSortedTracks
    GetTracks
    Item
    Load
    Move
    Remove
    Save
Name
    foobar2000 v1.1.13
ApplicationPath
    C:\Program Files (x86)\foobar2000\foobar2000.exe
MediaLibrary
    GetSortedTracks
    GetTracks
    Rescan
Minimized
    True
Playback
    FormatTitle
    FormatTitleEx
    Next
    Pause
    Previous
    Random
    Seek
    SeekRelative
    Start
    Stop
ProfilePath
    file://C:\Users\user\AppData\Roaming\foobar2000

Solution 2

For those who find the accepted answer not working (look here for the reasons) - 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
Share:
17,966

Related videos on Youtube

f.rodrigues
Author by

f.rodrigues

Art major and hobbyist programmer. Interested in Game-Development and Image-Manipulation(Moving and Still). SOreadytohelp

Updated on October 10, 2022

Comments

  • f.rodrigues
    f.rodrigues over 1 year

    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.

  • f.rodrigues
    f.rodrigues over 9 years
    It doesn't work well with com objects. It list some stuff, but I know some others that aren't showing.
  • Dmitry Grigoryev
    Dmitry Grigoryev about 8 years
    I tried this code with Excel.Application as ProgId and it doesn't seem to work (no attribute _prop_map_get_) on Python 3.3.
  • maxdebayser
    maxdebayser over 7 years
    Do you, by any chance, know of a way to list all "program IDs" available? I'm trying to run a microsoft program with python but I don't know if it has a COM object
  • z33k
    z33k over 5 years
    Any one found a way of doing this in Python3?
  • Matt Williams
    Matt Williams about 5 years
    This worked for me on Python 2.7 - I just had to change the {method} syntax in the print statements to make it compatible.
  • Melendowski
    Melendowski over 4 years
    This is a good answer but note that this will only work with the application object. If you want further objects and to stick with win32com.client.Dispatch(ProgID) method then you have to run the makepy.py file found at win32com\client\makepy.py a dialog will open up, select the appropriate library. See more info at pythonstudio.us/introduction-2/… . Its the paragraph that starts with In order to generate the Python files that support a specific COM object, . If you do this then you can now use dir() & go through all props and methods
  • Melendowski
    Melendowski over 4 years
    All methods will be listed with dir() and then r/w properties are listed under _prop_mat_put_ and read only props under _prop_map_get_.
  • ZMJ
    ZMJ almost 4 years
    This method is working for me. Is ther any way to print the signature of the method (argument type and number, return type)?