<p>对于那些发现<a href="https://stackoverflow.com/a/27371403/4465708">the accepted answer</a>不起作用的人(我猜有些东西随着<code>pywin32</code>在Python3中的工作方式而改变了)-仍然有一种方法可以获得具有<code>_prop_map_get_</code>属性(将对象的字段作为键保存的dict)的对象。您只需使用<code>win32com.client.gencache.EnsureDispatch()</code>创建主应用程序对象。</p>
<p>下面是我编写的一个便利函数,它列出了通过这种方式创建的已传递COM对象的字段和方法:</p>
<pre><code>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")
</code></pre>
<p>对于使用<code>win32com.client.gencache.EnsureDispatch("Excel.Application")</code>创建的Excel对象,其输出为:</p>
<pre><code>Members of 'Excel.Application' (Microsoft Excel):
Fields:
ActiveCell
ActiveChart
ActiveDialog
ActiveEncryptionSession
...
Workbooks
WorksheetFunction
Worksheets
_Default
Methods:
ActivateMicrosoftApp
AddChartAutoFormat
AddCustomList
Calculate
...
Union
Volatile
Wait
</code></pre>