对于那些发现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