无法导入comtypes.gen

4 投票
3 回答
14449 浏览
提问于 2025-04-16 05:16

我在Python 2.6上安装了comtypes 0.6.2。如果我尝试这样做:

import comtypes.gen

我得到的结果是:

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    import comtypes.gen
ImportError: No module named gen

不过,像import comtypesimport comtypes.client这样的导入都能正常工作。

我到底哪里出错了呢?

从名字上看,comtypes.gen似乎是生成的代码?如果是这样的话,我在导入之前需要做什么准备吗?我现在不是以管理员身份登录。这会导致代码生成失败吗?

编辑: 上面的这个问题通过reload(comtypes.gen)解决了(不过我不太明白为什么)。但是,现在from comtypes.gen import IWshRuntimeLibrary却不工作了。这个符号应该是生成代码的一部分。那么我该怎么让这个代码生成出来呢?

3 个回答

0

最近我换了新办公室,所以我需要修改@frederick的脚本,让它重新生成所有办公室的对象。

import os
import glob
import comtypes.client
# You may want to change the office path
msoffice=r'C:\Program Files (x86)\Microsoft Office\root\Office16'

#Generates wrapper for a given library
def wrap(com_lib):
    try:
         comtypes.client.GetModule(com_lib)
    except:
         print("Failed to wrap {0}".format( com_lib))

sys32dir = os.path.join(os.environ["SystemRoot"], "system32")

#Generate wrappers for all ocx's in system32
for lib in glob.glob(os.path.join(sys32dir, "*.ocx")):
    wrap(lib)

#Generate for all dll's in system32
for lib in glob.glob(os.path.join(msoffice, "*.tlb")):
    wrap(lib)

for lib in glob.glob(os.path.join(msoffice, "*.olb")):
    wrap(lib)

# And a special case for Excel
excel=os.path.join(msoffice,"excel.exe")
wrap(excel)
1

也许,正如所说的,comtypes这个包里的gen包并不存在。你可以去你的site-packages文件夹里看看(在Windows上通常是C:\Python26\Lib\site-packages,记得把C:\Python26换成你自己安装的目录),看看里面有没有一个comtypes\gen的子文件夹。

5

经过一些实验,我找到了解决办法。

我发现:

  1. 导入 comtypes.client 时,会自动创建一个叫 comtypes.gen 的子包。
  2. 调用 comtypes.client.GetModule("MyComLib") 会为 "MyComLib" 生成一个包装器。

所以,下面的代码对我来说解决了问题:

import os
import glob 
import comtypes.client

#Generates wrapper for a given library 
def wrap(com_lib): 
    try: 
         comtypes.client.GetModule(com_lib) 
    except: 
         print "Failed to wrap {0}".format(com_lib) 

sys32dir = os.path.join(os.environ["SystemRoot"], "system32") 

#Generate wrappers for all ocx's in system32 
for lib in glob.glob(os.path.join(sys32dir, "*.ocx")): 
    wrap(lib) 

#Generate for all dll's in system32 
for lib in glob.glob(os.path.join(sys32dir, "*.tlb")): 
    wrap(lib) 

有了相关的 COM 库包装后,现在我可以顺利访问 IWshRuntimeLibrary 了。

撰写回答