python - 无法导入 comtypes.gen

标签 python import comtypes

我在 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 不起作用。该符号应该是生成代码的一部分。那么如何生成这段代码呢?

最佳答案

好吧,经过一些实验,我找到了解决方案。

我发现:

  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。

关于python - 无法导入 comtypes.gen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3898670/

相关文章:

mysql - 如何标记 MySQL 中的重复条目?

reactjs - Vue.js 如何导入 SVG 标志

Python在函数中导入包

python - 导入 pywinauto(或 comtypes)会破坏现有的 COM 对象

python - 更改输入文件的路径,comtypes

Python:体面的配置文件格式

c++ - Boost Python 中的跨模块依赖关系

python - Pandas :根据条件展平列?

python - 验证输入值 - PySimpleGUI

python - 在 python 中使用 COM dll?