home *** CD-ROM | disk | FTP | other *** search
/ One Click 11 / OneClick11.iso / Bancos de Dados / Conversao / Mysql2Excel / Setup.exe / Mysql2Excel.exe / win32com / client / gencache.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-06-23  |  21.9 KB  |  595 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''Manages the cache of generated Python code.
  5.  
  6. Description
  7.   This file manages the cache of generated Python code.  When run from the 
  8.   command line, it also provides a number of options for managing that cache.
  9.   
  10. Implementation
  11.   Each typelib is generated into a filename of format "{guid}x{lcid}x{major}x{minor}.py"
  12.   
  13.   An external persistant dictionary maps from all known IIDs in all known type libraries
  14.   to the type library itself.
  15.   
  16.   Thus, whenever Python code knows the IID of an object, it can find the IID, LCID and version of
  17.   the type library which supports it.  Given this information, it can find the Python module
  18.   with the support.
  19.   
  20.   If necessary, this support can be generated on the fly.
  21.   
  22. Hacks, to do, etc
  23.   Currently just uses a pickled dictionary, but should used some sort of indexed file.
  24.   Maybe an OLE2 compound file, or a bsddb file?
  25. '''
  26. import pywintypes
  27. import os
  28. import string
  29. import sys
  30. import pythoncom
  31. import win32com
  32. import win32com.client as win32com
  33. import glob
  34. import traceback
  35. import CLSIDToClass
  36. clsidToTypelib = { }
  37. demandGeneratedTypeLibraries = { }
  38.  
  39. def __init__():
  40.     
  41.     try:
  42.         _LoadDicts()
  43.     except IOError:
  44.         Rebuild()
  45.  
  46.  
  47. pickleVersion = 1
  48.  
  49. def _SaveDicts():
  50.     import cPickle
  51.     f = open(os.path.join(GetGeneratePath(), 'dicts.dat'), 'wb')
  52.     
  53.     try:
  54.         p = cPickle.Pickler(f)
  55.         p.dump(pickleVersion)
  56.         p.dump(clsidToTypelib)
  57.     finally:
  58.         f.close()
  59.  
  60.  
  61.  
  62. def _LoadDicts():
  63.     global clsidToTypelib
  64.     import cPickle
  65.     
  66.     try:
  67.         f = open(os.path.join(win32com.__gen_path__, 'dicts.dat'), 'rb')
  68.     except AttributeError:
  69.         return None
  70.  
  71.     
  72.     try:
  73.         p = cPickle.Unpickler(f)
  74.         version = p.load()
  75.         clsidToTypelib = p.load()
  76.     finally:
  77.         f.close()
  78.  
  79.  
  80.  
  81. def GetGeneratedFileName(clsid, lcid, major, minor):
  82.     '''Given the clsid, lcid, major and  minor for a type lib, return
  83. \tthe file name (no extension) providing this support.
  84. \t'''
  85.     return string.upper(str(clsid))[1:-1] + 'x%sx%sx%s' % (lcid, major, minor)
  86.  
  87.  
  88. def SplitGeneratedFileName(fname):
  89.     '''Reverse of GetGeneratedFileName()
  90. \t'''
  91.     return tuple(string.split(fname, 'x', 4))
  92.  
  93.  
  94. def GetGeneratePath():
  95.     '''Returns the name of the path to generate to.
  96. \tChecks the directory is OK.
  97. \t'''
  98.     
  99.     try:
  100.         os.mkdir(win32com.__gen_path__)
  101.     except os.error:
  102.         pass
  103.  
  104.     
  105.     try:
  106.         fname = os.path.join(win32com.__gen_path__, '__init__.py')
  107.         os.stat(fname)
  108.     except os.error:
  109.         f = open(fname, 'w')
  110.         f.write('# Generated file - this directory may be deleted to reset the COM cache...\n')
  111.         f.write('import win32com\n')
  112.         f.write('if __path__[:-1] != win32com.__gen_path__: __path__.append(win32com.__gen_path__)\n')
  113.         f.close()
  114.  
  115.     return win32com.__gen_path__
  116.  
  117.  
  118. def GetClassForProgID(progid):
  119.     '''Get a Python class for a Program ID
  120. \t
  121. \tGiven a Program ID, return a Python class which wraps the COM object
  122. \t
  123. \tReturns the Python class, or None if no module is available.
  124. \t
  125. \tParams
  126. \tprogid -- A COM ProgramID or IID (eg, "Word.Application")
  127. \t'''
  128.     clsid = pywintypes.IID(progid)
  129.     return GetClassForCLSID(clsid)
  130.  
  131.  
  132. def GetClassForCLSID(clsid):
  133.     '''Get a Python class for a CLSID
  134. \t
  135. \tGiven a CLSID, return a Python class which wraps the COM object
  136. \t
  137. \tReturns the Python class, or None if no module is available.
  138. \t
  139. \tParams
  140. \tclsid -- A COM CLSID (or string repr of one)
  141. \t'''
  142.     clsid = str(clsid)
  143.     if CLSIDToClass.HasClass(clsid):
  144.         return CLSIDToClass.GetClass(clsid)
  145.     
  146.     mod = GetModuleForCLSID(clsid)
  147.     if mod is None:
  148.         return None
  149.     
  150.     
  151.     try:
  152.         return CLSIDToClass.GetClass(clsid)
  153.     except KeyError:
  154.         return None
  155.  
  156.  
  157.  
  158. def GetModuleForProgID(progid):
  159.     '''Get a Python module for a Program ID
  160. \t
  161. \tGiven a Program ID, return a Python module which contains the
  162. \tclass which wraps the COM object.
  163. \t
  164. \tReturns the Python module, or None if no module is available.
  165. \t
  166. \tParams
  167. \tprogid -- A COM ProgramID or IID (eg, "Word.Application")
  168. \t'''
  169.     
  170.     try:
  171.         iid = pywintypes.IID(progid)
  172.     except pywintypes.com_error:
  173.         return None
  174.  
  175.     return GetModuleForCLSID(iid)
  176.  
  177.  
  178. def GetModuleForCLSID(clsid):
  179.     '''Get a Python module for a CLSID
  180. \t
  181. \tGiven a CLSID, return a Python module which contains the
  182. \tclass which wraps the COM object.
  183. \t
  184. \tReturns the Python module, or None if no module is available.
  185. \t
  186. \tParams
  187. \tprogid -- A COM CLSID (ie, not the description)
  188. \t'''
  189.     clsid_str = str(clsid)
  190.     
  191.     try:
  192.         (typelibCLSID, lcid, major, minor) = clsidToTypelib[clsid_str]
  193.     except KeyError:
  194.         return None
  195.  
  196.     mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  197.     if mod is not None:
  198.         sub_mod = mod.CLSIDToPackageMap.get(clsid_str)
  199.         if sub_mod is None:
  200.             sub_mod = mod.VTablesToPackageMap.get(clsid_str)
  201.         
  202.         if sub_mod is not None:
  203.             sub_mod_name = mod.__name__ + '.' + sub_mod
  204.             
  205.             try:
  206.                 __import__(sub_mod_name)
  207.             except ImportError:
  208.                 info = (typelibCLSID, lcid, major, minor)
  209.                 if demandGeneratedTypeLibraries.has_key(info):
  210.                     info = demandGeneratedTypeLibraries[info]
  211.                 
  212.                 import makepy
  213.                 makepy.GenerateChildFromTypeLibSpec(sub_mod, info)
  214.  
  215.             mod = sys.modules[sub_mod_name]
  216.         
  217.     
  218.     return mod
  219.  
  220.  
  221. def GetModuleForTypelib(typelibCLSID, lcid, major, minor):
  222.     '''Get a Python module for a type library ID
  223. \t
  224. \tGiven the CLSID of a typelibrary, return an imported Python module, 
  225. \telse None
  226. \t
  227. \tParams
  228. \ttypelibCLSID -- IID of the type library.
  229. \tmajor -- Integer major version.
  230. \tminor -- Integer minor version
  231. \tlcid -- Integer LCID for the library.
  232. \t'''
  233.     modName = GetGeneratedFileName(typelibCLSID, lcid, major, minor)
  234.     return _GetModule(modName)
  235.  
  236.  
  237. def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None, bGUIProgress = None, bForDemand = 0, bBuildHidden = 1):
  238.     '''Generate support for a type library.
  239. \t
  240. \tGiven the IID, LCID and version information for a type library, generate
  241. \tand import the necessary support files.
  242. \t
  243. \tReturns the Python module.  No exceptions are caught.
  244.  
  245. \tParams
  246. \ttypelibCLSID -- IID of the type library.
  247. \tmajor -- Integer major version.
  248. \tminor -- Integer minor version.
  249. \tlcid -- Integer LCID for the library.
  250. \tprogressInstance -- Instance to use as progress indicator, or None to
  251. \t                    use the GUI progress bar.
  252. \t'''
  253.     if bGUIProgress is not None:
  254.         print "The 'bGuiProgress' param to 'MakeModuleForTypelib' is obsolete."
  255.     
  256.     import makepy
  257.     
  258.     try:
  259.         makepy.GenerateFromTypeLibSpec((typelibCLSID, lcid, major, minor), progressInstance = progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  260.     except pywintypes.com_error:
  261.         return None
  262.  
  263.     return GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  264.  
  265.  
  266. def MakeModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = 0, bBuildHidden = 1):
  267.     '''Generate support for a type library.
  268. \t
  269. \tGiven a PyITypeLib interface generate and import the necessary support files.  This is useful
  270. \tfor getting makepy support for a typelibrary that is not registered - the caller can locate
  271. \tand load the type library itself, rather than relying on COM to find it.
  272. \t
  273. \tReturns the Python module.
  274.  
  275. \tParams
  276. \ttypelib_ob -- The type library itself
  277. \tprogressInstance -- Instance to use as progress indicator, or None to
  278. \t                    use the GUI progress bar.
  279. \t'''
  280.     import makepy
  281.     
  282.     try:
  283.         makepy.GenerateFromTypeLibSpec(typelib_ob, progressInstance = progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  284.     except pywintypes.com_error:
  285.         return None
  286.  
  287.     tla = typelib_ob.GetLibAttr()
  288.     guid = tla[0]
  289.     lcid = tla[1]
  290.     major = tla[3]
  291.     minor = tla[4]
  292.     return GetModuleForTypelib(guid, lcid, major, minor)
  293.  
  294.  
  295. def EnsureModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = 0, bBuildHidden = 1):
  296.     '''Check we have support for a type library, generating if not.
  297. \t
  298. \tGiven a PyITypeLib interface generate and import the necessary
  299. \tsupport files if necessary. This is useful for getting makepy support
  300. \tfor a typelibrary that is not registered - the caller can locate and
  301. \tload the type library itself, rather than relying on COM to find it.
  302. \t
  303. \tReturns the Python module.
  304.  
  305. \tParams
  306. \ttypelib_ob -- The type library itself
  307. \tprogressInstance -- Instance to use as progress indicator, or None to
  308. \t                    use the GUI progress bar.
  309. \t'''
  310.     tla = typelib_ob.GetLibAttr()
  311.     guid = tla[0]
  312.     lcid = tla[1]
  313.     major = tla[3]
  314.     minor = tla[4]
  315.     if bForDemand:
  316.         demandGeneratedTypeLibraries[(str(guid), lcid, major, minor)] = typelib_ob
  317.     
  318.     
  319.     try:
  320.         return GetModuleForTypelib(guid, lcid, major, minor)
  321.     except ImportError:
  322.         pass
  323.  
  324.     return MakeModuleForTypelibInterface(typelib_ob, progressInstance, bForDemand, bBuildHidden)
  325.  
  326.  
  327. def ForgetAboutTypelibInterface(typelib_ob):
  328.     '''Drop any references to a typelib previously added with EnsureModuleForTypelibInterface and forDemand'''
  329.     tla = typelib_ob.GetLibAttr()
  330.     guid = tla[0]
  331.     lcid = tla[1]
  332.     major = tla[3]
  333.     minor = tla[4]
  334.     info = (str(guid), lcid, major, minor)
  335.     
  336.     try:
  337.         del demandGeneratedTypeLibraries[info]
  338.     except KeyError:
  339.         print 'ForgetAboutTypelibInterface:: Warning - type library with info %s is not being remembered!' % (info,)
  340.  
  341.  
  342.  
  343. def EnsureModule(typelibCLSID, lcid, major, minor, progressInstance = None, bValidateFile = 1, bForDemand = 0, bBuildHidden = 1):
  344.     '''Ensure Python support is loaded for a type library, generating if necessary.
  345. \t
  346. \tGiven the IID, LCID and version information for a type library, check and if
  347. \tnecessary (re)generate, then import the necessary support files. If we regenerate the file, there
  348. \tis no way to totally snuff out all instances of the old module in Python, and thus we will regenerate the file more than necessary,
  349. \tunless makepy/genpy is modified accordingly.
  350. \t
  351. \t
  352. \tReturns the Python module.  No exceptions are caught during the generate process.
  353.  
  354. \tParams
  355. \ttypelibCLSID -- IID of the type library.
  356. \tmajor -- Integer major version.
  357. \tminor -- Integer minor version
  358. \tlcid -- Integer LCID for the library.
  359. \tprogressInstance -- Instance to use as progress indicator, or None to
  360. \t                    use the GUI progress bar.
  361. \tbValidateFile -- Whether or not to perform cache validation or not
  362. \tbForDemand -- Should a complete generation happen now, or on demand?
  363. \tbBuildHidden -- Should hidden members/attributes etc be generated?
  364. \t'''
  365.     bReloadNeeded = 0
  366.     
  367.     try:
  368.         
  369.         try:
  370.             module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  371.         except ImportError:
  372.             tlbAttr = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid).GetLibAttr()
  373.             
  374.             try:
  375.                 module = GetModuleForTypelib(typelibCLSID, tlbAttr[1], tlbAttr[3], tlbAttr[4])
  376.             except ImportError:
  377.                 module = None
  378.                 minor = tlbAttr[4]
  379.  
  380.  
  381.         if bValidateFile:
  382.             filePathPrefix = '%s\\%s' % (GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor))
  383.             filePath = filePathPrefix + '.py'
  384.             filePathPyc = filePathPrefix + '.py'
  385.             if __debug__:
  386.                 filePathPyc = filePathPyc + 'c'
  387.             else:
  388.                 filePathPyc = filePathPyc + 'o'
  389.             typLibPath = pythoncom.QueryPathOfRegTypeLib(typelibCLSID, major, minor, lcid)
  390.             tlbAttributes = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid).GetLibAttr()
  391.             import genpy
  392.             if module is not None and module.MinorVersion != tlbAttributes[4] or genpy.makepy_version != module.makepy_version:
  393.                 
  394.                 try:
  395.                     os.unlink(filePath)
  396.                 except os.error:
  397.                     pass
  398.  
  399.                 
  400.                 try:
  401.                     os.unlink(filePathPyc)
  402.                 except os.error:
  403.                     pass
  404.  
  405.                 if os.path.isdir(filePathPrefix):
  406.                     import shutil
  407.                     shutil.rmtree(filePathPrefix)
  408.                 
  409.                 minor = tlbAttributes[4]
  410.                 module = None
  411.                 bReloadNeeded = 1
  412.             elif module is not None:
  413.                 minor = module.MinorVersion
  414.                 filePathPrefix = '%s\\%s' % (GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor))
  415.                 filePath = filePathPrefix + '.py'
  416.                 filePathPyc = filePathPrefix + '.pyc'
  417.                 fModTimeSet = 0
  418.                 
  419.                 try:
  420.                     pyModTime = os.stat(filePath)[8]
  421.                     fModTimeSet = 1
  422.                 except os.error:
  423.                     e = None
  424.                     
  425.                     try:
  426.                         pyModTime = os.stat(filePathPyc)[8]
  427.                         fModTimeSet = 1
  428.                     except os.error:
  429.                         e = None
  430.  
  431.  
  432.                 typLibModTime = os.stat(str(typLibPath[:-1]))[8]
  433.                 if fModTimeSet and typLibModTime > pyModTime:
  434.                     bReloadNeeded = 1
  435.                     module = None
  436.                 
  437.             
  438.     except (ImportError, os.error):
  439.         module = None
  440.  
  441.     if module is None:
  442.         module = MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  443.         if bReloadNeeded:
  444.             module = reload(module)
  445.             AddModuleToCache(typelibCLSID, lcid, major, minor)
  446.         
  447.     
  448.     return module
  449.  
  450.  
  451. def EnsureDispatch(prog_id, bForDemand = 1):
  452.     '''Given a COM prog_id, return an object that is using makepy support, building if necessary'''
  453.     disp = win32com.client.Dispatch(prog_id)
  454.     if not disp.__dict__.get('CLSID'):
  455.         
  456.         try:
  457.             ti = disp._oleobj_.GetTypeInfo()
  458.             disp_clsid = ti.GetTypeAttr()[0]
  459.             (tlb, index) = ti.GetContainingTypeLib()
  460.             tla = tlb.GetLibAttr()
  461.             mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand = bForDemand)
  462.             GetModuleForCLSID(disp_clsid)
  463.             import CLSIDToClass
  464.             disp_class = CLSIDToClass.GetClass(str(disp_clsid))
  465.             disp = disp_class(disp._oleobj_)
  466.         except pythoncom.com_error:
  467.             raise TypeError, 'This COM object can not automate the makepy process - please run makepy manually for this object'
  468.  
  469.     
  470.     return disp
  471.  
  472.  
  473. def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1, bFlushNow = 1):
  474.     '''Add a newly generated file to the cache dictionary.
  475. \t'''
  476.     fname = GetGeneratedFileName(typelibclsid, lcid, major, minor)
  477.     mod = _GetModule(fname)
  478.     dict = mod.CLSIDToClassMap
  479.     for clsid, cls in dict.items():
  480.         clsidToTypelib[clsid] = (str(typelibclsid), mod.LCID, mod.MajorVersion, mod.MinorVersion)
  481.     
  482.     dict = mod.CLSIDToPackageMap
  483.     for clsid, name in dict.items():
  484.         clsidToTypelib[clsid] = (str(typelibclsid), mod.LCID, mod.MajorVersion, mod.MinorVersion)
  485.     
  486.     dict = mod.VTablesToClassMap
  487.     for clsid, cls in dict.items():
  488.         clsidToTypelib[clsid] = (str(typelibclsid), mod.LCID, mod.MajorVersion, mod.MinorVersion)
  489.     
  490.     dict = mod.VTablesToPackageMap
  491.     for clsid, cls in dict.items():
  492.         clsidToTypelib[clsid] = (str(typelibclsid), mod.LCID, mod.MajorVersion, mod.MinorVersion)
  493.     
  494.     if bFlushNow:
  495.         _SaveDicts()
  496.     
  497.  
  498.  
  499. def _GetModule(fname):
  500.     '''Given the name of a module in the gen_py directory, import and return it.
  501. \t'''
  502.     mod = __import__('win32com.gen_py.%s' % fname)
  503.     return getattr(getattr(mod, 'gen_py'), fname)
  504.  
  505.  
  506. def Rebuild(verbose = 1):
  507.     '''Rebuild the cache indexes from the file system.
  508. \t'''
  509.     clsidToTypelib.clear()
  510.     files = glob.glob(win32com.__gen_path__ + '\\*.py')
  511.     if verbose and len(files):
  512.         print 'Rebuilding cache of generated files for COM support...'
  513.     
  514.     for file in files:
  515.         name = os.path.splitext(os.path.split(file)[1])[0]
  516.         
  517.         try:
  518.             (iid, lcid, major, minor) = string.split(name, 'x')
  519.             ok = 1
  520.         except ValueError:
  521.             ok = 0
  522.  
  523.         if ok:
  524.             
  525.             try:
  526.                 iid = pywintypes.IID('{' + iid + '}')
  527.             except pywintypes.com_error:
  528.                 ok = 0
  529.  
  530.         
  531.         if ok:
  532.             if verbose:
  533.                 print 'Checking', name
  534.             
  535.             
  536.             try:
  537.                 AddModuleToCache(iid, lcid, major, minor, verbose, 0)
  538.             except:
  539.                 print 'Could not add module %s - %s: %s' % (name, sys.exc_info()[0], sys.exc_info()[1])
  540.  
  541.         elif verbose and name[0] != '_':
  542.             print 'Skipping module', name
  543.         
  544.     
  545.     if verbose and len(files):
  546.         print 'Done.'
  547.     
  548.     _SaveDicts()
  549.  
  550.  
  551. def _Dump():
  552.     print 'Cache is in directory', win32com.__gen_path__
  553.     files = glob.glob(win32com.__gen_path__ + '\\*.py')
  554.     for file in files:
  555.         name = os.path.splitext(os.path.split(file)[1])[0]
  556.         if name[0] != '_':
  557.             mod = _GetModule(name)
  558.             print '%s - %s' % (mod.__doc__, name)
  559.         
  560.     
  561.  
  562. __init__()
  563. usageString = '  Usage: gencache [-q] [-d] [-r]\n  \n         -q         - Quiet\n         -d         - Dump the cache (typelibrary description and filename).\n         -r         - Rebuild the cache dictionary from the existing .py files\n'
  564.  
  565. def usage():
  566.     print usageString
  567.     sys.exit(1)
  568.  
  569. if __name__ == '__main__':
  570.     import getopt
  571.     
  572.     try:
  573.         (opts, args) = getopt.getopt(sys.argv[1:], 'qrd')
  574.     except getopt.error:
  575.         message = None
  576.         print message
  577.         usage()
  578.  
  579.     if len(sys.argv) == 1 or args:
  580.         print usage()
  581.     
  582.     verbose = 1
  583.     for opt, val in opts:
  584.         if opt == '-d':
  585.             _Dump()
  586.         
  587.         if opt == '-r':
  588.             Rebuild(verbose)
  589.         
  590.         if opt == '-q':
  591.             verbose = 0
  592.         
  593.     
  594.  
  595.