makepy.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. # Originally written by Curt Hagenlocher, and various bits
  2. # and pieces by Mark Hammond (and now Greg Stein has had
  3. # a go too :-)
  4. # Note that the main worker code has been moved to genpy.py
  5. # As this is normally run from the command line, it reparses the code each time.
  6. # Now this is nothing more than the command line handler and public interface.
  7. # XXX - TO DO
  8. # XXX - Greg and Mark have some ideas for a revamp - just no
  9. # time - if you want to help, contact us for details.
  10. # Main idea is to drop the classes exported and move to a more
  11. # traditional data driven model.
  12. """Generate a .py file from an OLE TypeLibrary file.
  13. This module is concerned only with the actual writing of
  14. a .py file. It draws on the @build@ module, which builds
  15. the knowledge of a COM interface.
  16. """
  17. usageHelp = """ \
  18. Usage:
  19. makepy.py [-i] [-v|q] [-h] [-u] [-o output_file] [-d] [typelib, ...]
  20. -i -- Show information for the specified typelib.
  21. -v -- Verbose output.
  22. -q -- Quiet output.
  23. -h -- Do not generate hidden methods.
  24. -u -- Python 1.5 and earlier: Do NOT convert all Unicode objects to
  25. strings.
  26. Python 1.6 and later: Convert all Unicode objects to strings.
  27. -o -- Create output in a specified output file. If the path leading
  28. to the file does not exist, any missing directories will be
  29. created.
  30. NOTE: -o cannot be used with -d. This will generate an error.
  31. -d -- Generate the base code now and the class code on demand.
  32. Recommended for large type libraries.
  33. typelib -- A TLB, DLL, OCX or anything containing COM type information.
  34. If a typelib is not specified, a window containing a textbox
  35. will open from which you can select a registered type
  36. library.
  37. Examples:
  38. makepy.py -d
  39. Presents a list of registered type libraries from which you can make
  40. a selection.
  41. makepy.py -d "Microsoft Excel 8.0 Object Library"
  42. Generate support for the type library with the specified description
  43. (in this case, the MS Excel object model).
  44. """
  45. import sys, os, importlib, pythoncom
  46. from win32com.client import genpy, selecttlb, gencache
  47. from win32com.client import Dispatch
  48. bForDemandDefault = 0 # Default value of bForDemand - toggle this to change the world - see also gencache.py
  49. error = "makepy.error"
  50. def usage():
  51. sys.stderr.write (usageHelp)
  52. sys.exit(2)
  53. def ShowInfo(spec):
  54. if not spec:
  55. tlbSpec = selecttlb.SelectTlb(excludeFlags=selecttlb.FLAG_HIDDEN)
  56. if tlbSpec is None:
  57. return
  58. try:
  59. tlb = pythoncom.LoadRegTypeLib(tlbSpec.clsid, tlbSpec.major, tlbSpec.minor, tlbSpec.lcid)
  60. except pythoncom.com_error: # May be badly registered.
  61. sys.stderr.write("Warning - could not load registered typelib '%s'\n" % (tlbSpec.clsid))
  62. tlb = None
  63. infos = [(tlb, tlbSpec)]
  64. else:
  65. infos = GetTypeLibsForSpec(spec)
  66. for (tlb, tlbSpec) in infos:
  67. desc = tlbSpec.desc
  68. if desc is None:
  69. if tlb is None:
  70. desc = "<Could not load typelib %s>" % (tlbSpec.dll)
  71. else:
  72. desc = tlb.GetDocumentation(-1)[0]
  73. print(desc)
  74. print(" %s, lcid=%s, major=%s, minor=%s" % (tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor))
  75. print(" >>> # Use these commands in Python code to auto generate .py support")
  76. print(" >>> from win32com.client import gencache")
  77. print(" >>> gencache.EnsureModule('%s', %s, %s, %s)" % (tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor))
  78. class SimpleProgress(genpy.GeneratorProgress):
  79. """A simple progress class prints its output to stderr
  80. """
  81. def __init__(self, verboseLevel):
  82. self.verboseLevel = verboseLevel
  83. def Close(self):
  84. pass
  85. def Finished(self):
  86. if self.verboseLevel>1:
  87. sys.stderr.write("Generation complete..\n")
  88. def SetDescription(self, desc, maxticks = None):
  89. if self.verboseLevel:
  90. sys.stderr.write(desc + "\n")
  91. def Tick(self, desc = None):
  92. pass
  93. def VerboseProgress(self, desc, verboseLevel = 2):
  94. if self.verboseLevel >= verboseLevel:
  95. sys.stderr.write(desc + "\n")
  96. def LogBeginGenerate(self, filename):
  97. self.VerboseProgress("Generating to %s" % filename, 1)
  98. def LogWarning(self, desc):
  99. self.VerboseProgress("WARNING: " + desc, 1)
  100. class GUIProgress(SimpleProgress):
  101. def __init__(self, verboseLevel):
  102. # Import some modules we need to we can trap failure now.
  103. import win32ui, pywin
  104. SimpleProgress.__init__(self, verboseLevel)
  105. self.dialog = None
  106. def Close(self):
  107. if self.dialog is not None:
  108. self.dialog.Close()
  109. self.dialog = None
  110. def Starting(self, tlb_desc):
  111. SimpleProgress.Starting(self, tlb_desc)
  112. if self.dialog is None:
  113. from pywin.dialogs import status
  114. self.dialog=status.ThreadedStatusProgressDialog(tlb_desc)
  115. else:
  116. self.dialog.SetTitle(tlb_desc)
  117. def SetDescription(self, desc, maxticks = None):
  118. self.dialog.SetText(desc)
  119. if maxticks:
  120. self.dialog.SetMaxTicks(maxticks)
  121. def Tick(self, desc = None):
  122. self.dialog.Tick()
  123. if desc is not None:
  124. self.dialog.SetText(desc)
  125. def GetTypeLibsForSpec(arg):
  126. """Given an argument on the command line (either a file name, library
  127. description, or ProgID of an object) return a list of actual typelibs
  128. to use. """
  129. typelibs = []
  130. try:
  131. try:
  132. tlb = pythoncom.LoadTypeLib(arg)
  133. spec = selecttlb.TypelibSpec(None, 0,0,0)
  134. spec.FromTypelib(tlb, arg)
  135. typelibs.append((tlb, spec))
  136. except pythoncom.com_error:
  137. # See if it is a description
  138. tlbs = selecttlb.FindTlbsWithDescription(arg)
  139. if len(tlbs)==0:
  140. # Maybe it is the name of a COM object?
  141. try:
  142. ob = Dispatch(arg)
  143. # and if so, it must support typelib info
  144. tlb, index = ob._oleobj_.GetTypeInfo().GetContainingTypeLib()
  145. spec = selecttlb.TypelibSpec(None, 0,0,0)
  146. spec.FromTypelib(tlb)
  147. tlbs.append(spec)
  148. except pythoncom.com_error:
  149. pass
  150. if len(tlbs)==0:
  151. print("Could not locate a type library matching '%s'" % (arg))
  152. for spec in tlbs:
  153. # Version numbers not always reliable if enumerated from registry.
  154. # (as some libs use hex, other's dont. Both examples from MS, of course.)
  155. if spec.dll is None:
  156. tlb = pythoncom.LoadRegTypeLib(spec.clsid, spec.major, spec.minor, spec.lcid)
  157. else:
  158. tlb = pythoncom.LoadTypeLib(spec.dll)
  159. # We have a typelib, but it may not be exactly what we specified
  160. # (due to automatic version matching of COM). So we query what we really have!
  161. attr = tlb.GetLibAttr()
  162. spec.major = attr[3]
  163. spec.minor = attr[4]
  164. spec.lcid = attr[1]
  165. typelibs.append((tlb, spec))
  166. return typelibs
  167. except pythoncom.com_error:
  168. t,v,tb=sys.exc_info()
  169. sys.stderr.write ("Unable to load type library from '%s' - %s\n" % (arg, v))
  170. tb = None # Storing tb in a local is a cycle!
  171. sys.exit(1)
  172. def GenerateFromTypeLibSpec(typelibInfo, file = None, verboseLevel = None, progressInstance = None, bUnicodeToString=None, bForDemand = bForDemandDefault, bBuildHidden = 1):
  173. assert bUnicodeToString is None, "this is deprecated and will go away"
  174. if verboseLevel is None:
  175. verboseLevel = 0 # By default, we use no gui and no verbose level!
  176. if bForDemand and file is not None:
  177. raise RuntimeError("You can only perform a demand-build when the output goes to the gen_py directory")
  178. if isinstance(typelibInfo, tuple):
  179. # Tuple
  180. typelibCLSID, lcid, major, minor = typelibInfo
  181. tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid)
  182. spec = selecttlb.TypelibSpec(typelibCLSID, lcid, major, minor)
  183. spec.FromTypelib(tlb, str(typelibCLSID))
  184. typelibs = [(tlb, spec)]
  185. elif isinstance(typelibInfo, selecttlb.TypelibSpec):
  186. if typelibInfo.dll is None:
  187. # Version numbers not always reliable if enumerated from registry.
  188. tlb = pythoncom.LoadRegTypeLib(typelibInfo.clsid, typelibInfo.major, typelibInfo.minor, typelibInfo.lcid)
  189. else:
  190. tlb = pythoncom.LoadTypeLib(typelibInfo.dll)
  191. typelibs = [(tlb, typelibInfo)]
  192. elif hasattr(typelibInfo, "GetLibAttr"):
  193. # A real typelib object!
  194. # Could also use isinstance(typelibInfo, PyITypeLib) instead, but PyITypeLib is not directly exposed by pythoncom.
  195. # pythoncom.TypeIIDs[pythoncom.IID_ITypeLib] seems to work
  196. tla = typelibInfo.GetLibAttr()
  197. guid = tla[0]
  198. lcid = tla[1]
  199. major = tla[3]
  200. minor = tla[4]
  201. spec = selecttlb.TypelibSpec(guid, lcid, major, minor)
  202. typelibs = [(typelibInfo, spec)]
  203. else:
  204. typelibs = GetTypeLibsForSpec(typelibInfo)
  205. if progressInstance is None:
  206. progressInstance = SimpleProgress(verboseLevel)
  207. progress = progressInstance
  208. bToGenDir = (file is None)
  209. for typelib, info in typelibs:
  210. gen = genpy.Generator(typelib, info.dll, progress, bBuildHidden=bBuildHidden)
  211. if file is None:
  212. this_name = gencache.GetGeneratedFileName(info.clsid, info.lcid, info.major, info.minor)
  213. full_name = os.path.join(gencache.GetGeneratePath(), this_name)
  214. if bForDemand:
  215. try: os.unlink(full_name + ".py")
  216. except os.error: pass
  217. try: os.unlink(full_name + ".pyc")
  218. except os.error: pass
  219. try: os.unlink(full_name + ".pyo")
  220. except os.error: pass
  221. if not os.path.isdir(full_name):
  222. os.mkdir(full_name)
  223. outputName = os.path.join(full_name, "__init__.py")
  224. else:
  225. outputName = full_name + ".py"
  226. fileUse = gen.open_writer(outputName)
  227. progress.LogBeginGenerate(outputName)
  228. else:
  229. fileUse = file
  230. worked = False
  231. try:
  232. gen.generate(fileUse, bForDemand)
  233. worked = True
  234. finally:
  235. if file is None:
  236. gen.finish_writer(outputName, fileUse, worked)
  237. importlib.invalidate_caches()
  238. if bToGenDir:
  239. progress.SetDescription("Importing module")
  240. gencache.AddModuleToCache(info.clsid, info.lcid, info.major, info.minor)
  241. progress.Close()
  242. def GenerateChildFromTypeLibSpec(child, typelibInfo, verboseLevel = None, progressInstance = None, bUnicodeToString=None):
  243. assert bUnicodeToString is None, "this is deprecated and will go away"
  244. if verboseLevel is None:
  245. verboseLevel = 0 # By default, we use no gui, and no verbose level for the children.
  246. if type(typelibInfo)==type(()):
  247. typelibCLSID, lcid, major, minor = typelibInfo
  248. tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid)
  249. else:
  250. tlb = typelibInfo
  251. tla = typelibInfo.GetLibAttr()
  252. typelibCLSID = tla[0]
  253. lcid = tla[1]
  254. major = tla[3]
  255. minor = tla[4]
  256. spec = selecttlb.TypelibSpec(typelibCLSID, lcid, major, minor)
  257. spec.FromTypelib(tlb, str(typelibCLSID))
  258. typelibs = [(tlb, spec)]
  259. if progressInstance is None:
  260. progressInstance = SimpleProgress(verboseLevel)
  261. progress = progressInstance
  262. for typelib, info in typelibs:
  263. dir_name = gencache.GetGeneratedFileName(info.clsid, info.lcid, info.major, info.minor)
  264. dir_path_name = os.path.join(gencache.GetGeneratePath(), dir_name)
  265. progress.LogBeginGenerate(dir_path_name)
  266. gen = genpy.Generator(typelib, info.dll, progress)
  267. gen.generate_child(child, dir_path_name)
  268. progress.SetDescription("Importing module")
  269. importlib.invalidate_caches()
  270. __import__("win32com.gen_py." + dir_name + "." + child)
  271. progress.Close()
  272. def main():
  273. import getopt
  274. hiddenSpec = 1
  275. outputName = None
  276. verboseLevel = 1
  277. doit = 1
  278. bForDemand = bForDemandDefault
  279. try:
  280. opts, args = getopt.getopt(sys.argv[1:], 'vo:huiqd')
  281. for o,v in opts:
  282. if o=='-h':
  283. hiddenSpec = 0
  284. elif o=='-o':
  285. outputName = v
  286. elif o=='-v':
  287. verboseLevel = verboseLevel + 1
  288. elif o=='-q':
  289. verboseLevel = verboseLevel - 1
  290. elif o=='-i':
  291. if len(args)==0:
  292. ShowInfo(None)
  293. else:
  294. for arg in args:
  295. ShowInfo(arg)
  296. doit = 0
  297. elif o=='-d':
  298. bForDemand = not bForDemand
  299. except (getopt.error, error) as msg:
  300. sys.stderr.write (str(msg) + "\n")
  301. usage()
  302. if bForDemand and outputName is not None:
  303. sys.stderr.write("Can not use -d and -o together\n")
  304. usage()
  305. if not doit:
  306. return 0
  307. if len(args)==0:
  308. rc = selecttlb.SelectTlb()
  309. if rc is None:
  310. sys.exit(1)
  311. args = [ rc ]
  312. if outputName is not None:
  313. path = os.path.dirname(outputName)
  314. if path != '' and not os.path.exists(path):
  315. os.makedirs(path)
  316. if sys.version_info > (3,0):
  317. f = open(outputName, "wt", encoding="mbcs")
  318. else:
  319. import codecs # not available in py3k.
  320. f = codecs.open(outputName, "w", "mbcs")
  321. else:
  322. f = None
  323. for arg in args:
  324. GenerateFromTypeLibSpec(arg, f, verboseLevel = verboseLevel, bForDemand = bForDemand, bBuildHidden = hiddenSpec)
  325. if f:
  326. f.close()
  327. if __name__=='__main__':
  328. rc = main()
  329. if rc:
  330. sys.exit(rc)
  331. sys.exit(0)