尝试访问COM对象属性时出现错误POINTER(IUnknown)

时间:2017-03-14 19:06:27

标签: python-3.x com comtypes

Python中的这段代码不起作用:

from comtypes import client
word = client.CreateObject("Word.Application")
word.Documents.Open("C:\\test.docx")

我收到此错误消息:

Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
doc = word.Documents.Open("test.docx")
AttributeError: 'POINTER(IUnknown)' object has no attribute 'Documents'

使用类 Excel.Appliation 的类似代码也会产生同样的错误。使用 InternetExplorer.Application 进行的另一项测试有效。所以这似乎是Office的一个问题。

我还在VBScript中测试了相同的代码并且工作了。

该代码适用于Windows7-64bits和Office 2013.无法运行的计算机是Windows10-64bits和Office 365.两台计算机中的Python版本均为3.6-64位。

1 个答案:

答案 0 :(得分:0)

这不是一个好的解决方案,但我想我能够忍受它。我现在正在使用此代码:

from comtypes import client
word = client.CreateObject("Word.Application", dynamic = True)
word.Visible = True
word.Documents.Open("test.docx")
word.Documents[0].SaveAs("test.pdf", 17)
word.Documents[0].Close()

重要的是word.Visible = True行和dynamic = True参数。没有它们,找不到 Documents 集合。

相关问题