列出COMobj中的所有方法

2024-05-23 21:56:12 发布

您现在位置:Python中文网/ 问答频道 /正文

有可能吗?

一行字:

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

for methods in com_object:
    print methods

我得到了com_object.__dict__,其中列出:

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

大多数都是空的,除了:

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

但我不知道如何访问这些类型的任何内容。


Tags: inimportcomclientforobjectusernamewin32com
3条回答

对于那些发现the accepted answer不起作用的人(我猜有些东西随着pywin32在Python3中的工作方式而改变了)-仍然有一种方法可以获得具有_prop_map_get_属性(将对象的字段作为键保存的dict)的对象。您只需使用win32com.client.gencache.EnsureDispatch()创建主应用程序对象。

下面是我编写的一个便利函数,它列出了通过这种方式创建的已传递COM对象的字段和方法:

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")

对于使用win32com.client.gencache.EnsureDispatch("Excel.Application")创建的Excel对象,其输出为:

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

刚刚找到了大多数方法:

以下是方法:

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

下面是一个示例输出,其中包含ProgID = "Foobar2000.Application.0.7"

输出:

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

要列出对象的属性,可以使用dir()函数。这是python的内置函数,不需要导入。请尝试以下操作:

打印目录(对象)

查看对象的属性。

相关问题 更多 >