Cannot import comtypes.gen

I have comtypes 0.6.2 installed on Python 2.6. If I try this:

import comtypes.gen 

I get:

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

Other imports, such as import comtypes and import comtypes.client , however, work fine.

What am I doing wrong?

comtypes.gen code seem to comtypes.gen generated on behalf of comtypes.gen ? If so, do I need certain preparatory steps before importing? I am not registered as an administrator. Could this lead to code failure?

Edit: The above problem is solved with reload(comtypes.gen) (I don't understand how, though). However, now from comtypes.gen import IWshRuntimeLibrary does not work. This character must be part of the generated code. So how can I get this code?

+4
source share
3 answers

Well, after some experimentation, I have a solution.

I found that:

  • Importing comtypes.client automatically creates a comtypes.gen .
  • Calling comtypes.client.GetModule("MyComLib") creates 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 in system32 for lib in glob.glob(os.path.join(sys32dir, "*.ocx")): wrap(lib) #Generate for all dll in system32 for lib in glob.glob(os.path.join(sys32dir, "*.tlb")): wrap(lib) 

Having the appropriate COM interface, I can now access the IWshRuntimeLibrary just fine.

+4
source

Perhaps, as said, the package package packages in comptypes does not exist. Check your site’s folder (C: \ Python26 \ Lib \ site-packages on Windows, replace C: \ Python26 with the installation directory) for the comtypes \ gen subfolder.

+1
source

I recently got a new office, and I had to extend the @frederick script to generate all 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 in system32 for lib in glob.glob(os.path.join(sys32dir, "*.ocx")): wrap(lib) #Generate for all dll 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) 
0
source

All Articles