Can't import comtypes.gen

混江龙づ霸主 提交于 2019-12-05 15:17:48

Well, after some experimentation, I have the solution.

I've found that:

  1. Importing comtypes.client automatically creates the comtypes.gen subpackage.
  2. Calling comtypes.client.GetModule("MyComLib") generates a wrapper for "MyComLib".

So the following code did the job for me:

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) 

Having the relevant COM lib wrapped, now I can access IWshRuntimeLibrary just fine.

Perhaps, as it says, the package gen package in comptypes doesn't exist. Check your site-packages folder (C:\Python26\Lib\site-packages on Windows, substitute the C:\Python26 with your installation directory) for a comtypes\gen subfolder.

recently i got the new office, and i had to extend the script of @frederick to generate all the office objects again.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!