home *** CD-ROM | disk | FTP | other *** search
/ PC World 2002 May / PCWorld_2002-05_cd.bin / Software / TemaCD / activepython / ActivePython-2.1.1.msi / Python21_win32com_client_makepy.py < prev    next >
Encoding:
Python Source  |  2001-07-26  |  11.5 KB  |  361 lines

  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.  
  5. # Note that the main worker code has been moved to genpy.py
  6. # As this is normally run from the command line, it reparses the code each time.  
  7. # Now this is nothing more than the command line handler and public interface.
  8.  
  9. # XXX - TO DO
  10. # XXX - Greg and Mark have some ideas for a revamp - just no
  11. #       time - if you want to help, contact us for details.
  12. #       Main idea is to drop the classes exported and move to a more
  13. #       traditional data driven model.
  14.  
  15. """Generate a .py file from an OLE TypeLibrary file.
  16.  
  17.  
  18.  This module is concerned only with the actual writing of
  19.  a .py file.  It draws on the @build@ module, which builds 
  20.  the knowledge of a COM interface.
  21.  
  22. """
  23. usageHelp = """ \
  24. Usage:
  25.  
  26.   makepy.py [-h] [-x0|1] [-u] [-o filename] [-d] [typelib, ...]
  27.   
  28.   typelib -- A TLB, DLL, OCX, Description, or possibly something else.
  29.   -h    -- Do not generate hidden methods.
  30.   -u    -- Python 1.5 and earlier: Do not convert all Unicode objects to strings.
  31.            Python 1.6 and later: Do convert all Unicode objects to strings.
  32.   -o outputFile -- Generate to named file - dont generate to standard directory.
  33.   -i [typelib] -- Show info for specified typelib, or select the typelib if not specified.
  34.   -v    -- Verbose output
  35.   -q    -- Quiet output
  36.   -d    -- Generate the base code now and classes code on demand
  37.   
  38. Examples:
  39.   makepy.py
  40.     Present a list of type libraries.
  41.     
  42.   makepy.py "Microsoft Excel 8.0 Object Library"
  43.     Generate support for the typelibrary with the specified description
  44.     (in this case, MS Excel object model)
  45.  
  46. """
  47.  
  48. import genpy, string, sys, os, types, pythoncom
  49. import selecttlb
  50. import gencache
  51. from win32com.client import NeedUnicodeConversions
  52.  
  53. error = "makepy.error"
  54.  
  55. def usage():
  56.     sys.stderr.write (usageHelp)
  57.     sys.exit(2)
  58.  
  59. def ShowInfo(spec):
  60.     if not spec:
  61.         tlbSpec = selecttlb.SelectTlb(excludeFlags=selecttlb.FLAG_HIDDEN)
  62.         if tlbSpec is None:
  63.             return
  64.         try:
  65.             tlb = pythoncom.LoadRegTypeLib(tlbSpec.clsid, tlbSpec.major, tlbSpec.minor, tlbSpec.lcid)
  66.         except pythoncom.com_error: # May be badly registered.
  67.             sys.stderr.write("Warning - could not load registered typelib '%s'\n" % (tlbSpec.clsid))
  68.             tlb = None
  69.         
  70.         infos = [(tlb, tlbSpec)]
  71.     else:
  72.         infos = GetTypeLibsForSpec(spec)
  73.     for (tlb, tlbSpec) in infos:
  74.         desc = tlbSpec.desc
  75.         if desc is None:
  76.             if tlb is None:
  77.                 desc = "<Could not load typelib %s>" % (tlbSpec.dll)
  78.             else:
  79.                 desc = tlb.GetDocumentation(-1)[0]
  80.         print desc
  81.         print " %s, lcid=%s, major=%s, minor=%s" % (tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor)
  82.         print " >>> # Use these commands in Python code to auto generate .py support"
  83.         print " >>> from win32com.client import gencache"
  84.         print " >>> gencache.EnsureModule('%s', %s, %s, %s)" % (tlbSpec.clsid, tlbSpec.lcid, tlbSpec.major, tlbSpec.minor)
  85.  
  86. class SimpleProgress(genpy.GeneratorProgress):
  87.     """A simple progress class prints its output to stderr
  88.     """
  89.     def __init__(self, verboseLevel):
  90.         self.verboseLevel = verboseLevel
  91.     def Close(self):
  92.         pass
  93.     def Finished(self):
  94.         if self.verboseLevel>1:
  95.             sys.stderr.write("Generation complete..\n")
  96.     def SetDescription(self, desc, maxticks = None):
  97.         if self.verboseLevel:
  98.             sys.stderr.write(desc + "\n")
  99.     def Tick(self, desc = None):
  100.         pass
  101.  
  102.     def VerboseProgress(self, desc, verboseLevel = 2):
  103.         if self.verboseLevel >= verboseLevel:
  104.             sys.stderr.write(desc + "\n")
  105.  
  106.     def LogBeginGenerate(self, filename):
  107.         self.VerboseProgress("Generating to %s" % filename, 1)
  108.     
  109.     def LogWarning(self, desc):
  110.         self.VerboseProgress("WARNING: " + desc, 1)
  111.  
  112. class GUIProgress(SimpleProgress):
  113.     def __init__(self, verboseLevel):
  114.         # Import some modules we need to we can trap failure now.
  115.         import win32ui, pywin
  116.         SimpleProgress.__init__(self, verboseLevel)
  117.         self.dialog = None
  118.         
  119.     def Close(self):
  120.         if self.dialog is not None:
  121.             self.dialog.Close()
  122.             self.dialog = None
  123.         
  124.     def Starting(self, tlb_desc):
  125.         SimpleProgress.Starting(self, tlb_desc)
  126.         if self.dialog is None:
  127.             from pywin.dialogs import status
  128.             self.dialog=status.StatusProgressDialog(tlb_desc)
  129.         else:
  130.             self.dialog.SetTitle(tlb_desc)
  131.         
  132.     def SetDescription(self, desc, maxticks = None):
  133.         self.dialog.SetText(desc)
  134.         if maxticks:
  135.             self.dialog.SetMaxTicks(maxticks)
  136.  
  137.     def Tick(self, desc = None):
  138.         self.dialog.Tick()
  139.         if desc is not None:
  140.             self.dialog.SetText(desc)
  141.  
  142. def GetTypeLibsForSpec(arg):
  143.     """Given an argument on the command line (either a file name or a library description)
  144.     return a list of actual typelibs to use.
  145.     """
  146.     typelibs = []
  147.     try:
  148.         try:
  149.             tlb = pythoncom.LoadTypeLib(arg)
  150.             spec = selecttlb.TypelibSpec(None, 0,0,0)
  151.             spec.FromTypelib(tlb, arg)
  152.             typelibs.append((tlb, spec))
  153.         except pythoncom.com_error:
  154.             # See if it is a description
  155.             tlbs = selecttlb.FindTlbsWithDescription(arg)
  156.             if len(tlbs)==0:
  157.                 print "Could not locate a type library matching '%s'" % (arg)
  158.             for spec in tlbs:
  159.                 tlb = pythoncom.LoadRegTypeLib(spec.clsid, spec.major, spec.minor, spec.lcid)
  160.                 # We have a typelib, but it may not be exactly what we specified
  161.                 # (due to automatic version matching of COM).  So we query what we really have!
  162.                 attr = tlb.GetLibAttr()
  163.                 spec.major = attr[3]
  164.                 spec.minor = attr[4]
  165.                 spec.lcid = attr[1]
  166.                 typelibs.append((tlb, spec))
  167.         return typelibs
  168.     except pythoncom.com_error:
  169.         t,v,tb=sys.exc_info()
  170.         sys.stderr.write ("Unable to load type library from '%s' - %s\n" % (arg, v))
  171.         tb = None # Storing tb in a local is a cycle!
  172.         sys.exit(1)
  173.  
  174. def GenerateFromTypeLibSpec(typelibInfo, file = None, verboseLevel = None, progressInstance = None, bUnicodeToString=NeedUnicodeConversions, bQuiet = None, bGUIProgress = None, bForDemand = 0, bBuildHidden = 1):
  175.     if bQuiet is not None or bGUIProgress is not None:
  176.         print "Please dont use the bQuiet or bGUIProgress params"
  177.         print "use the 'verboseLevel', and 'progressClass' params"
  178.     if verboseLevel is None:
  179.         verboseLevel = 0 # By default, we use a gui, and no verbose level!
  180.  
  181.     if bForDemand and file is not None:
  182.         raise RuntimeError, "You can only perform a demand-build when the output goes to the gen_py directory"
  183.     if type(typelibInfo)==type(()):
  184.         # Tuple
  185.         typelibCLSID, lcid, major, minor  = typelibInfo
  186.         tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid)
  187.         spec = selecttlb.TypelibSpec(typelibCLSID, lcid, major, minor)
  188.         spec.FromTypelib(tlb, str(typelibCLSID))
  189.         typelibs = [(tlb, spec)]
  190.     elif type(typelibInfo)==types.InstanceType:
  191.         tlb = pythoncom.LoadRegTypeLib(typelibInfo.clsid, typelibInfo.major, typelibInfo.minor, typelibInfo.lcid)
  192.         typelibs = [(tlb, typelibInfo)]
  193.     elif hasattr(typelibInfo, "GetLibAttr"):
  194.         # A real typelib object!
  195.         tla = typelibInfo.GetLibAttr()
  196.         guid = tla[0]
  197.         lcid = tla[1]
  198.         major = tla[3]
  199.         minor = tla[4]
  200.         spec = selecttlb.TypelibSpec(guid, lcid, major, minor)
  201.         typelibs = [(typelibInfo, spec)]
  202.     else:
  203.         typelibs = GetTypeLibsForSpec(typelibInfo)
  204.  
  205.     if progressInstance is None:
  206.         try:
  207.             if not bForDemand: # Only go for GUI progress if not doing a demand-import
  208.                 # Win9x console programs don't seem to like our GUI!
  209.                 # (Actually, NT/2k wouldnt object to having them threaded - later!)
  210.                 import win32api, win32con
  211.                 if win32api.GetVersionEx()[3]==win32con.VER_PLATFORM_WIN32_NT:
  212.                     bMakeGuiProgress = 1
  213.                 else:
  214.                     try:
  215.                         win32api.GetConsoleTitle()
  216.                         # Have a console - can't handle GUI
  217.                         bMakeGuiProgress = 0
  218.                     except win32api.error:
  219.                         # no console - we can have a GUI
  220.                         bMakeGuiProgress = 1
  221.                 if bMakeGuiProgress:
  222.                     progressInstance = GUIProgress(verboseLevel)
  223.         except ImportError: # No Pythonwin GUI around.
  224.             pass
  225.     if progressInstance is None:
  226.         progressInstance = SimpleProgress(verboseLevel)
  227.     progress = progressInstance
  228.  
  229.     bToGenDir = (file is None)
  230.  
  231.     for typelib, info in typelibs:
  232.         if file is None:
  233.             this_name = gencache.GetGeneratedFileName(info.clsid, info.lcid, info.major, info.minor)
  234.             full_name = os.path.join(gencache.GetGeneratePath(), this_name)
  235.             if bForDemand:
  236.                 try: os.unlink(full_name + ".py")
  237.                 except os.error: pass
  238.                 try: os.unlink(full_name + ".pyc")
  239.                 except os.error: pass
  240.                 try: os.unlink(full_name + ".pyo")
  241.                 except os.error: pass
  242.                 if not os.path.isdir(full_name):
  243.                     os.mkdir(full_name)
  244.                 outputName = os.path.join(full_name, "__init__.py")
  245.             else:
  246.                 outputName = full_name + ".py"
  247.             fileUse = open(outputName, "wt")
  248.             progress.LogBeginGenerate(outputName)
  249.         else:
  250.             fileUse = file
  251.  
  252.         gen = genpy.Generator(typelib, info.dll, progress, bUnicodeToString=bUnicodeToString, bBuildHidden=bBuildHidden)
  253.  
  254.         gen.generate(fileUse, bForDemand)
  255.         
  256.         if file is None:
  257.             fileUse.close()
  258.         
  259.         if bToGenDir:
  260.             progress.SetDescription("Importing module")
  261.             gencache.AddModuleToCache(info.clsid, info.lcid, info.major, info.minor)
  262.  
  263.     progress.Close()
  264.  
  265. def GenerateChildFromTypeLibSpec(child, typelibInfo, verboseLevel = None, progressInstance = None, bUnicodeToString=NeedUnicodeConversions):
  266.     if verboseLevel is None:
  267.         verboseLevel = 0 # By default, we use no gui, and no verbose level for the children.
  268.     if type(typelibInfo)==type(()):
  269.         typelibCLSID, lcid, major, minor  = typelibInfo
  270.         tlb = pythoncom.LoadRegTypeLib(typelibCLSID, major, minor, lcid)
  271.     else:
  272.         tlb = typelibInfo
  273.         tla = typelibInfo.GetLibAttr()
  274.         typelibCLSID = tla[0]
  275.         lcid = tla[1]
  276.         major = tla[3]
  277.         minor = tla[4]
  278.     spec = selecttlb.TypelibSpec(typelibCLSID, lcid, major, minor)
  279.     spec.FromTypelib(tlb, str(typelibCLSID))
  280.     typelibs = [(tlb, spec)]
  281.  
  282.     if progressInstance is None:
  283.         progressInstance = SimpleProgress(verboseLevel)
  284.     progress = progressInstance
  285.  
  286.     for typelib, info in typelibs:
  287.         dir_name = gencache.GetGeneratedFileName(info.clsid, info.lcid, info.major, info.minor)
  288.         dir_path_name = os.path.join(gencache.GetGeneratePath(), dir_name)
  289.         progress.LogBeginGenerate(dir_path_name)
  290.  
  291.         gen = genpy.Generator(typelib, info.dll, progress, bUnicodeToString=bUnicodeToString)
  292.         gen.generate_child(child, dir_path_name)
  293.         progress.SetDescription("Importing module")
  294.         __import__("win32com.gen_py." + dir_name + "." + child)
  295.     progress.Close()
  296.  
  297. def main():
  298.     import getopt
  299.     hiddenSpec = 1
  300.     bUnicodeToString = NeedUnicodeConversions
  301.     outputName = None
  302.     verboseLevel = 1
  303.     doit = 1
  304.     bForDemand = 0
  305.     try:
  306.         opts, args = getopt.getopt(sys.argv[1:], 'vo:huiqd')
  307.         for o,v in opts:
  308.             if o=='-h':
  309.                 hiddenSpec = 0
  310.             elif o=='-u':
  311.                 bUnicodeToString = not NeedUnicodeConversions
  312.             elif o=='-o':
  313.                 outputName = v
  314.             elif o=='-v':
  315.                 verboseLevel = verboseLevel + 1
  316.             elif o=='-q':
  317.                 verboseLevel = verboseLevel - 1
  318.             elif o=='-i':
  319.                 if len(args)==0:
  320.                     ShowInfo(None)
  321.                 else:
  322.                     for arg in args:
  323.                         ShowInfo(arg)
  324.                 doit = 0
  325.             elif o=='-d':
  326.                 bForDemand = 1
  327.  
  328.     except (getopt.error, error), msg:
  329.         sys.stderr.write (str(msg) + "\n")
  330.         usage()
  331.  
  332.     if bForDemand and outputName is not None:
  333.         sys.stderr.write("Can not use -d and -o together\n")
  334.         usage()
  335.  
  336.     if not doit:
  337.         return 0        
  338.     if len(args)==0:
  339.         rc = selecttlb.SelectTlb()
  340.         if rc is None:
  341.             sys.exit(1)
  342.         args = [ rc ]
  343.  
  344.     if outputName is not None:
  345.         f = open(outputName, "w")
  346.     else:
  347.         f = None
  348.  
  349.     for arg in args:
  350.         GenerateFromTypeLibSpec(arg, f, verboseLevel = verboseLevel, bForDemand = bForDemand, bBuildHidden = hiddenSpec)
  351.  
  352.     if f:    
  353.         f.close()
  354.  
  355.  
  356. if __name__=='__main__':
  357.     rc = main()
  358.     if rc:
  359.         sys.exit(rc)
  360.     sys.exit(0)
  361.