gencache.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. """Manages the cache of generated Python code.
  2. Description
  3. This file manages the cache of generated Python code. When run from the
  4. command line, it also provides a number of options for managing that cache.
  5. Implementation
  6. Each typelib is generated into a filename of format "{guid}x{lcid}x{major}x{minor}.py"
  7. An external persistant dictionary maps from all known IIDs in all known type libraries
  8. to the type library itself.
  9. Thus, whenever Python code knows the IID of an object, it can find the IID, LCID and version of
  10. the type library which supports it. Given this information, it can find the Python module
  11. with the support.
  12. If necessary, this support can be generated on the fly.
  13. Hacks, to do, etc
  14. Currently just uses a pickled dictionary, but should used some sort of indexed file.
  15. Maybe an OLE2 compound file, or a bsddb file?
  16. """
  17. import pywintypes, os, sys
  18. import pythoncom
  19. import win32com, win32com.client
  20. import glob
  21. import traceback
  22. from . import CLSIDToClass
  23. import operator
  24. from importlib import reload
  25. bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also makepy.py
  26. # The global dictionary
  27. clsidToTypelib = {}
  28. # If we have a different version of the typelib generated, this
  29. # maps the "requested version" to the "generated version".
  30. versionRedirectMap = {}
  31. # There is no reason we *must* be readonly in a .zip, but we are now,
  32. # Rather than check for ".zip" or other tricks, PEP302 defines
  33. # a "__loader__" attribute, so we use that.
  34. # (Later, it may become necessary to check if the __loader__ can update files,
  35. # as a .zip loader potentially could - but punt all that until a need arises)
  36. is_readonly = is_zip = hasattr(win32com, "__loader__") and hasattr(win32com.__loader__, "archive")
  37. # A dictionary of ITypeLibrary objects for demand generation explicitly handed to us
  38. # Keyed by usual clsid, lcid, major, minor
  39. demandGeneratedTypeLibraries = {}
  40. import pickle as pickle
  41. def __init__():
  42. # Initialize the module. Called once explicitly at module import below.
  43. try:
  44. _LoadDicts()
  45. except IOError:
  46. Rebuild()
  47. pickleVersion = 1
  48. def _SaveDicts():
  49. if is_readonly:
  50. raise RuntimeError("Trying to write to a readonly gencache ('%s')!" \
  51. % win32com.__gen_path__)
  52. f = open(os.path.join(GetGeneratePath(), "dicts.dat"), "wb")
  53. try:
  54. p = pickle.Pickler(f)
  55. p.dump(pickleVersion)
  56. p.dump(clsidToTypelib)
  57. finally:
  58. f.close()
  59. def _LoadDicts():
  60. # Load the dictionary from a .zip file if that is where we live.
  61. if is_zip:
  62. import io as io
  63. loader = win32com.__loader__
  64. arc_path = loader.archive
  65. dicts_path = os.path.join(win32com.__gen_path__, "dicts.dat")
  66. if dicts_path.startswith(arc_path):
  67. dicts_path = dicts_path[len(arc_path)+1:]
  68. else:
  69. # Hm. See below.
  70. return
  71. try:
  72. data = loader.get_data(dicts_path)
  73. except AttributeError:
  74. # The __loader__ has no get_data method. See below.
  75. return
  76. except IOError:
  77. # Our gencache is in a .zip file (and almost certainly readonly)
  78. # but no dicts file. That actually needn't be fatal for a frozen
  79. # application. Assuming they call "EnsureModule" with the same
  80. # typelib IDs they have been frozen with, that EnsureModule will
  81. # correctly re-build the dicts on the fly. However, objects that
  82. # rely on the gencache but have not done an EnsureModule will
  83. # fail (but their apps are likely to fail running from source
  84. # with a clean gencache anyway, as then they would be getting
  85. # Dynamic objects until the cache is built - so the best answer
  86. # for these apps is to call EnsureModule, rather than freezing
  87. # the dict)
  88. return
  89. f = io.BytesIO(data)
  90. else:
  91. # NOTE: IOError on file open must be caught by caller.
  92. f = open(os.path.join(win32com.__gen_path__, "dicts.dat"), "rb")
  93. try:
  94. p = pickle.Unpickler(f)
  95. version = p.load()
  96. global clsidToTypelib
  97. clsidToTypelib = p.load()
  98. versionRedirectMap.clear()
  99. finally:
  100. f.close()
  101. def GetGeneratedFileName(clsid, lcid, major, minor):
  102. """Given the clsid, lcid, major and minor for a type lib, return
  103. the file name (no extension) providing this support.
  104. """
  105. return str(clsid).upper()[1:-1] + "x%sx%sx%s" % (lcid, major, minor)
  106. def SplitGeneratedFileName(fname):
  107. """Reverse of GetGeneratedFileName()
  108. """
  109. return tuple(fname.split('x',4))
  110. def GetGeneratePath():
  111. """Returns the name of the path to generate to.
  112. Checks the directory is OK.
  113. """
  114. assert not is_readonly, "Why do you want the genpath for a readonly store?"
  115. try:
  116. os.makedirs(win32com.__gen_path__)
  117. #os.mkdir(win32com.__gen_path__)
  118. except os.error:
  119. pass
  120. try:
  121. fname = os.path.join(win32com.__gen_path__, "__init__.py")
  122. os.stat(fname)
  123. except os.error:
  124. f = open(fname,"w")
  125. f.write('# Generated file - this directory may be deleted to reset the COM cache...\n')
  126. f.write('import win32com\n')
  127. f.write('if __path__[:-1] != win32com.__gen_path__: __path__.append(win32com.__gen_path__)\n')
  128. f.close()
  129. return win32com.__gen_path__
  130. #
  131. # The helpers for win32com.client.Dispatch and OCX clients.
  132. #
  133. def GetClassForProgID(progid):
  134. """Get a Python class for a Program ID
  135. Given a Program ID, return a Python class which wraps the COM object
  136. Returns the Python class, or None if no module is available.
  137. Params
  138. progid -- A COM ProgramID or IID (eg, "Word.Application")
  139. """
  140. clsid = pywintypes.IID(progid) # This auto-converts named to IDs.
  141. return GetClassForCLSID(clsid)
  142. def GetClassForCLSID(clsid):
  143. """Get a Python class for a CLSID
  144. Given a CLSID, return a Python class which wraps the COM object
  145. Returns the Python class, or None if no module is available.
  146. Params
  147. clsid -- A COM CLSID (or string repr of one)
  148. """
  149. # first, take a short-cut - we may already have generated support ready-to-roll.
  150. clsid = str(clsid)
  151. if CLSIDToClass.HasClass(clsid):
  152. return CLSIDToClass.GetClass(clsid)
  153. mod = GetModuleForCLSID(clsid)
  154. if mod is None:
  155. return None
  156. try:
  157. return CLSIDToClass.GetClass(clsid)
  158. except KeyError:
  159. return None
  160. def GetModuleForProgID(progid):
  161. """Get a Python module for a Program ID
  162. Given a Program ID, return a Python module which contains the
  163. class which wraps the COM object.
  164. Returns the Python module, or None if no module is available.
  165. Params
  166. progid -- A COM ProgramID or IID (eg, "Word.Application")
  167. """
  168. try:
  169. iid = pywintypes.IID(progid)
  170. except pywintypes.com_error:
  171. return None
  172. return GetModuleForCLSID(iid)
  173. def GetModuleForCLSID(clsid):
  174. """Get a Python module for a CLSID
  175. Given a CLSID, return a Python module which contains the
  176. class which wraps the COM object.
  177. Returns the Python module, or None if no module is available.
  178. Params
  179. progid -- A COM CLSID (ie, not the description)
  180. """
  181. clsid_str = str(clsid)
  182. try:
  183. typelibCLSID, lcid, major, minor = clsidToTypelib[clsid_str]
  184. except KeyError:
  185. return None
  186. try:
  187. mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  188. except ImportError:
  189. mod = None
  190. if mod is not None:
  191. sub_mod = mod.CLSIDToPackageMap.get(clsid_str)
  192. if sub_mod is None:
  193. sub_mod = mod.VTablesToPackageMap.get(clsid_str)
  194. if sub_mod is not None:
  195. sub_mod_name = mod.__name__ + "." + sub_mod
  196. try:
  197. __import__(sub_mod_name)
  198. except ImportError:
  199. info = typelibCLSID, lcid, major, minor
  200. # Force the generation. If this typelibrary has explicitly been added,
  201. # use it (it may not be registered, causing a lookup by clsid to fail)
  202. if info in demandGeneratedTypeLibraries:
  203. info = demandGeneratedTypeLibraries[info]
  204. from . import makepy
  205. makepy.GenerateChildFromTypeLibSpec(sub_mod, info)
  206. # Generate does an import...
  207. mod = sys.modules[sub_mod_name]
  208. return mod
  209. def GetModuleForTypelib(typelibCLSID, lcid, major, minor):
  210. """Get a Python module for a type library ID
  211. Given the CLSID of a typelibrary, return an imported Python module,
  212. else None
  213. Params
  214. typelibCLSID -- IID of the type library.
  215. major -- Integer major version.
  216. minor -- Integer minor version
  217. lcid -- Integer LCID for the library.
  218. """
  219. modName = GetGeneratedFileName(typelibCLSID, lcid, major, minor)
  220. mod = _GetModule(modName)
  221. # If the import worked, it doesn't mean we have actually added this
  222. # module to our cache though - check that here.
  223. if "_in_gencache_" not in mod.__dict__:
  224. AddModuleToCache(typelibCLSID, lcid, major, minor)
  225. assert "_in_gencache_" in mod.__dict__
  226. return mod
  227. def MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
  228. """Generate support for a type library.
  229. Given the IID, LCID and version information for a type library, generate
  230. and import the necessary support files.
  231. Returns the Python module. No exceptions are caught.
  232. Params
  233. typelibCLSID -- IID of the type library.
  234. major -- Integer major version.
  235. minor -- Integer minor version.
  236. lcid -- Integer LCID for the library.
  237. progressInstance -- Instance to use as progress indicator, or None to
  238. use the GUI progress bar.
  239. """
  240. from . import makepy
  241. makepy.GenerateFromTypeLibSpec( (typelibCLSID, lcid, major, minor), progressInstance=progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  242. return GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  243. def MakeModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
  244. """Generate support for a type library.
  245. Given a PyITypeLib interface generate and import the necessary support files. This is useful
  246. for getting makepy support for a typelibrary that is not registered - the caller can locate
  247. and load the type library itself, rather than relying on COM to find it.
  248. Returns the Python module.
  249. Params
  250. typelib_ob -- The type library itself
  251. progressInstance -- Instance to use as progress indicator, or None to
  252. use the GUI progress bar.
  253. """
  254. from . import makepy
  255. try:
  256. makepy.GenerateFromTypeLibSpec( typelib_ob, progressInstance=progressInstance, bForDemand = bForDemandDefault, bBuildHidden = bBuildHidden)
  257. except pywintypes.com_error:
  258. return None
  259. tla = typelib_ob.GetLibAttr()
  260. guid = tla[0]
  261. lcid = tla[1]
  262. major = tla[3]
  263. minor = tla[4]
  264. return GetModuleForTypelib(guid, lcid, major, minor)
  265. def EnsureModuleForTypelibInterface(typelib_ob, progressInstance = None, bForDemand = bForDemandDefault, bBuildHidden = 1):
  266. """Check we have support for a type library, generating if not.
  267. Given a PyITypeLib interface generate and import the necessary
  268. support files if necessary. This is useful for getting makepy support
  269. for a typelibrary that is not registered - the caller can locate and
  270. load the type library itself, rather than relying on COM to find it.
  271. Returns the Python module.
  272. Params
  273. typelib_ob -- The type library itself
  274. progressInstance -- Instance to use as progress indicator, or None to
  275. use the GUI progress bar.
  276. """
  277. tla = typelib_ob.GetLibAttr()
  278. guid = tla[0]
  279. lcid = tla[1]
  280. major = tla[3]
  281. minor = tla[4]
  282. #If demand generated, save the typelib interface away for later use
  283. if bForDemand:
  284. demandGeneratedTypeLibraries[(str(guid), lcid, major, minor)] = typelib_ob
  285. try:
  286. return GetModuleForTypelib(guid, lcid, major, minor)
  287. except ImportError:
  288. pass
  289. # Generate it.
  290. return MakeModuleForTypelibInterface(typelib_ob, progressInstance, bForDemand, bBuildHidden)
  291. def ForgetAboutTypelibInterface(typelib_ob):
  292. """Drop any references to a typelib previously added with EnsureModuleForTypelibInterface and forDemand"""
  293. tla = typelib_ob.GetLibAttr()
  294. guid = tla[0]
  295. lcid = tla[1]
  296. major = tla[3]
  297. minor = tla[4]
  298. info = str(guid), lcid, major, minor
  299. try:
  300. del demandGeneratedTypeLibraries[info]
  301. except KeyError:
  302. # Not worth raising an exception - maybe they dont know we only remember for demand generated, etc.
  303. print("ForgetAboutTypelibInterface:: Warning - type library with info %s is not being remembered!" % (info,))
  304. # and drop any version redirects to it
  305. for key, val in list(versionRedirectMap.items()):
  306. if val==info:
  307. del versionRedirectMap[key]
  308. def EnsureModule(typelibCLSID, lcid, major, minor, progressInstance = None, bValidateFile=not is_readonly, bForDemand = bForDemandDefault, bBuildHidden = 1):
  309. """Ensure Python support is loaded for a type library, generating if necessary.
  310. Given the IID, LCID and version information for a type library, check and if
  311. necessary (re)generate, then import the necessary support files. If we regenerate the file, there
  312. is no way to totally snuff out all instances of the old module in Python, and thus we will regenerate the file more than necessary,
  313. unless makepy/genpy is modified accordingly.
  314. Returns the Python module. No exceptions are caught during the generate process.
  315. Params
  316. typelibCLSID -- IID of the type library.
  317. major -- Integer major version.
  318. minor -- Integer minor version
  319. lcid -- Integer LCID for the library.
  320. progressInstance -- Instance to use as progress indicator, or None to
  321. use the GUI progress bar.
  322. bValidateFile -- Whether or not to perform cache validation or not
  323. bForDemand -- Should a complete generation happen now, or on demand?
  324. bBuildHidden -- Should hidden members/attributes etc be generated?
  325. """
  326. bReloadNeeded = 0
  327. try:
  328. try:
  329. module = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  330. except ImportError:
  331. # If we get an ImportError
  332. # We may still find a valid cache file under a different MinorVersion #
  333. # (which windows will search out for us)
  334. #print "Loading reg typelib", typelibCLSID, major, minor, lcid
  335. module = None
  336. try:
  337. tlbAttr = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid).GetLibAttr()
  338. # if the above line doesn't throw a pythoncom.com_error, check if
  339. # it is actually a different lib than we requested, and if so, suck it in
  340. if tlbAttr[1] != lcid or tlbAttr[4]!=minor:
  341. #print "Trying 2nd minor #", tlbAttr[1], tlbAttr[3], tlbAttr[4]
  342. try:
  343. module = GetModuleForTypelib(typelibCLSID, tlbAttr[1], tlbAttr[3], tlbAttr[4])
  344. except ImportError:
  345. # We don't have a module, but we do have a better minor
  346. # version - remember that.
  347. minor = tlbAttr[4]
  348. # else module remains None
  349. except pythoncom.com_error:
  350. # couldn't load any typelib - mod remains None
  351. pass
  352. if module is not None and bValidateFile:
  353. assert not is_readonly, "Can't validate in a read-only gencache"
  354. try:
  355. typLibPath = pythoncom.QueryPathOfRegTypeLib(typelibCLSID, major, minor, lcid)
  356. # windows seems to add an extra \0 (via the underlying BSTR)
  357. # The mainwin toolkit does not add this erroneous \0
  358. if typLibPath[-1]=='\0':
  359. typLibPath=typLibPath[:-1]
  360. suf = getattr(os.path, "supports_unicode_filenames", 0)
  361. if not suf:
  362. # can't pass unicode filenames directly - convert
  363. try:
  364. typLibPath=typLibPath.encode(sys.getfilesystemencoding())
  365. except AttributeError: # no sys.getfilesystemencoding
  366. typLibPath=str(typLibPath)
  367. tlbAttributes = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid).GetLibAttr()
  368. except pythoncom.com_error:
  369. # We have a module, but no type lib - we should still
  370. # run with what we have though - the typelib may not be
  371. # deployed here.
  372. bValidateFile = 0
  373. if module is not None and bValidateFile:
  374. assert not is_readonly, "Can't validate in a read-only gencache"
  375. filePathPrefix = "%s\\%s" % (GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor))
  376. filePath = filePathPrefix + ".py"
  377. filePathPyc = filePathPrefix + ".py"
  378. if __debug__:
  379. filePathPyc = filePathPyc + "c"
  380. else:
  381. filePathPyc = filePathPyc + "o"
  382. # Verify that type library is up to date.
  383. # If we have a differing MinorVersion or genpy has bumped versions, update the file
  384. from . import genpy
  385. if module.MinorVersion != tlbAttributes[4] or genpy.makepy_version != module.makepy_version:
  386. #print "Version skew: %d, %d" % (module.MinorVersion, tlbAttributes[4])
  387. # try to erase the bad file from the cache
  388. try:
  389. os.unlink(filePath)
  390. except os.error:
  391. pass
  392. try:
  393. os.unlink(filePathPyc)
  394. except os.error:
  395. pass
  396. if os.path.isdir(filePathPrefix):
  397. import shutil
  398. shutil.rmtree(filePathPrefix)
  399. minor = tlbAttributes[4]
  400. module = None
  401. bReloadNeeded = 1
  402. else:
  403. minor = module.MinorVersion
  404. filePathPrefix = "%s\\%s" % (GetGeneratePath(), GetGeneratedFileName(typelibCLSID, lcid, major, minor))
  405. filePath = filePathPrefix + ".py"
  406. filePathPyc = filePathPrefix + ".pyc"
  407. #print "Trying py stat: ", filePath
  408. fModTimeSet = 0
  409. try:
  410. pyModTime = os.stat(filePath)[8]
  411. fModTimeSet = 1
  412. except os.error as e:
  413. # If .py file fails, try .pyc file
  414. #print "Trying pyc stat", filePathPyc
  415. try:
  416. pyModTime = os.stat(filePathPyc)[8]
  417. fModTimeSet = 1
  418. except os.error as e:
  419. pass
  420. #print "Trying stat typelib", pyModTime
  421. #print str(typLibPath)
  422. typLibModTime = os.stat(typLibPath)[8]
  423. if fModTimeSet and (typLibModTime > pyModTime):
  424. bReloadNeeded = 1
  425. module = None
  426. except (ImportError, os.error):
  427. module = None
  428. if module is None:
  429. # We need to build an item. If we are in a read-only cache, we
  430. # can't/don't want to do this - so before giving up, check for
  431. # a different minor version in our cache - according to COM, this is OK
  432. if is_readonly:
  433. key = str(typelibCLSID), lcid, major, minor
  434. # If we have been asked before, get last result.
  435. try:
  436. return versionRedirectMap[key]
  437. except KeyError:
  438. pass
  439. # Find other candidates.
  440. items = []
  441. for desc in GetGeneratedInfos():
  442. if key[0]==desc[0] and key[1]==desc[1] and key[2]==desc[2]:
  443. items.append(desc)
  444. if items:
  445. # Items are all identical, except for last tuple element
  446. # We want the latest minor version we have - so just sort and grab last
  447. items.sort()
  448. new_minor = items[-1][3]
  449. ret = GetModuleForTypelib(typelibCLSID, lcid, major, new_minor)
  450. else:
  451. ret = None
  452. # remember and return
  453. versionRedirectMap[key] = ret
  454. return ret
  455. #print "Rebuilding: ", major, minor
  456. module = MakeModuleForTypelib(typelibCLSID, lcid, major, minor, progressInstance, bForDemand = bForDemand, bBuildHidden = bBuildHidden)
  457. # If we replaced something, reload it
  458. if bReloadNeeded:
  459. module = reload(module)
  460. AddModuleToCache(typelibCLSID, lcid, major, minor)
  461. return module
  462. def EnsureDispatch(prog_id, bForDemand = 1): # New fn, so we default the new demand feature to on!
  463. """Given a COM prog_id, return an object that is using makepy support, building if necessary"""
  464. disp = win32com.client.Dispatch(prog_id)
  465. if not disp.__dict__.get("CLSID"): # Eeek - no makepy support - try and build it.
  466. try:
  467. ti = disp._oleobj_.GetTypeInfo()
  468. disp_clsid = ti.GetTypeAttr()[0]
  469. tlb, index = ti.GetContainingTypeLib()
  470. tla = tlb.GetLibAttr()
  471. mod = EnsureModule(tla[0], tla[1], tla[3], tla[4], bForDemand=bForDemand)
  472. GetModuleForCLSID(disp_clsid)
  473. # Get the class from the module.
  474. from . import CLSIDToClass
  475. disp_class = CLSIDToClass.GetClass(str(disp_clsid))
  476. disp = disp_class(disp._oleobj_)
  477. except pythoncom.com_error:
  478. raise TypeError("This COM object can not automate the makepy process - please run makepy manually for this object")
  479. return disp
  480. def AddModuleToCache(typelibclsid, lcid, major, minor, verbose = 1, bFlushNow = not is_readonly):
  481. """Add a newly generated file to the cache dictionary.
  482. """
  483. fname = GetGeneratedFileName(typelibclsid, lcid, major, minor)
  484. mod = _GetModule(fname)
  485. # if mod._in_gencache_ is already true, then we are reloading this
  486. # module - this doesn't mean anything special though!
  487. mod._in_gencache_ = 1
  488. info = str(typelibclsid), lcid, major, minor
  489. dict_modified = False
  490. def SetTypelibForAllClsids(dict):
  491. nonlocal dict_modified
  492. for clsid, cls in dict.items():
  493. if clsidToTypelib.get(clsid) != info:
  494. clsidToTypelib[clsid] = info
  495. dict_modified = True
  496. SetTypelibForAllClsids(mod.CLSIDToClassMap)
  497. SetTypelibForAllClsids(mod.CLSIDToPackageMap)
  498. SetTypelibForAllClsids(mod.VTablesToClassMap)
  499. SetTypelibForAllClsids(mod.VTablesToPackageMap)
  500. # If this lib was previously redirected, drop it
  501. if info in versionRedirectMap:
  502. del versionRedirectMap[info]
  503. if bFlushNow and dict_modified:
  504. _SaveDicts()
  505. def GetGeneratedInfos():
  506. zip_pos = win32com.__gen_path__.find(".zip\\")
  507. if zip_pos >= 0:
  508. import zipfile
  509. zip_file = win32com.__gen_path__[:zip_pos+4]
  510. zip_path = win32com.__gen_path__[zip_pos+5:].replace("\\", "/")
  511. zf = zipfile.ZipFile(zip_file)
  512. infos = {}
  513. for n in zf.namelist():
  514. if not n.startswith(zip_path):
  515. continue
  516. base = n[len(zip_path)+1:].split("/")[0]
  517. try:
  518. iid, lcid, major, minor = base.split("x")
  519. lcid = int(lcid)
  520. major = int(major)
  521. minor = int(minor)
  522. iid = pywintypes.IID("{" + iid + "}")
  523. except ValueError:
  524. continue
  525. except pywintypes.com_error:
  526. # invalid IID
  527. continue
  528. infos[(iid, lcid, major, minor)] = 1
  529. zf.close()
  530. return list(infos.keys())
  531. else:
  532. # on the file system
  533. files = glob.glob(win32com.__gen_path__+ "\\*")
  534. ret = []
  535. for file in files:
  536. if not os.path.isdir(file) and not os.path.splitext(file)[1]==".py":
  537. continue
  538. name = os.path.splitext(os.path.split(file)[1])[0]
  539. try:
  540. iid, lcid, major, minor = name.split("x")
  541. iid = pywintypes.IID("{" + iid + "}")
  542. lcid = int(lcid)
  543. major = int(major)
  544. minor = int(minor)
  545. except ValueError:
  546. continue
  547. except pywintypes.com_error:
  548. # invalid IID
  549. continue
  550. ret.append((iid, lcid, major, minor))
  551. return ret
  552. def _GetModule(fname):
  553. """Given the name of a module in the gen_py directory, import and return it.
  554. """
  555. mod_name = "win32com.gen_py.%s" % fname
  556. mod = __import__(mod_name)
  557. return sys.modules[mod_name]
  558. def Rebuild(verbose = 1):
  559. """Rebuild the cache indexes from the file system.
  560. """
  561. clsidToTypelib.clear()
  562. infos = GetGeneratedInfos()
  563. if verbose and len(infos): # Dont bother reporting this when directory is empty!
  564. print("Rebuilding cache of generated files for COM support...")
  565. for info in infos:
  566. iid, lcid, major, minor = info
  567. if verbose:
  568. print("Checking", GetGeneratedFileName(*info))
  569. try:
  570. AddModuleToCache(iid, lcid, major, minor, verbose, 0)
  571. except:
  572. print("Could not add module %s - %s: %s" % (info, sys.exc_info()[0],sys.exc_info()[1]))
  573. if verbose and len(infos): # Dont bother reporting this when directory is empty!
  574. print("Done.")
  575. _SaveDicts()
  576. def _Dump():
  577. print("Cache is in directory", win32com.__gen_path__)
  578. # Build a unique dir
  579. d = {}
  580. for clsid, (typelibCLSID, lcid, major, minor) in clsidToTypelib.items():
  581. d[typelibCLSID, lcid, major, minor] = None
  582. for typelibCLSID, lcid, major, minor in d.keys():
  583. mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor)
  584. print("%s - %s" % (mod.__doc__, typelibCLSID))
  585. # Boot up
  586. __init__()
  587. def usage():
  588. usageString = """\
  589. Usage: gencache [-q] [-d] [-r]
  590. -q - Quiet
  591. -d - Dump the cache (typelibrary description and filename).
  592. -r - Rebuild the cache dictionary from the existing .py files
  593. """
  594. print(usageString)
  595. sys.exit(1)
  596. if __name__=='__main__':
  597. import getopt
  598. try:
  599. opts, args = getopt.getopt(sys.argv[1:], "qrd")
  600. except getopt.error as message:
  601. print(message)
  602. usage()
  603. # we only have options - complain about real args, or none at all!
  604. if len(sys.argv)==1 or args:
  605. print(usage())
  606. verbose = 1
  607. for opt, val in opts:
  608. if opt=='-d': # Dump
  609. _Dump()
  610. if opt=='-r':
  611. Rebuild(verbose)
  612. if opt=='-q':
  613. verbose = 0