我在 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 comtypes
和 import comtypes.client
等其他导入工作正常。
我做错了什么?
从名字上看comtypes.gen
好像是生成代码吧?如果是这样,我在导入前是否需要某些准备步骤?我没有以管理员身份登录。这会导致代码生成失败吗?
编辑:
上面的问题通过 reload(comtypes.gen)
解决了(不过我不明白怎么做)。但是,现在 from comtypes.gen import IWshRuntimeLibrary
不起作用。该符号应该是生成代码的一部分。那么如何生成这段代码呢?
最佳答案
好吧,经过一些实验,我找到了解决方案。
我发现:
- 导入
comtypes.client
会自动创建comtypes.gen
子包。 - 调用
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。
关于python - 无法导入 comtypes.gen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3898670/