Can't import comtypes.gen

Frederick The Fool picture Frederick The Fool · Oct 10, 2010 · Viewed 9.8k times · Source

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 like import comtypes and import comtypes.client, however, work fine.

What am I doing wrong?

From the name it seems comtypes.gen is generated code? If so, do I need certain preparatory steps before importing? I'm not logged in as administrator. Could that cause code generation to fail?

Edit: The above problem is solved with a reload(comtypes.gen) (I don't understand how, though). However, now from comtypes.gen import IWshRuntimeLibrary is not working. This symbol should be part of a generated code. So how do I get this code to be generated?

Answer

Frederick The Fool picture Frederick The Fool · Oct 10, 2010

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.