home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 10 Tools / 10-Tools.zip / pyos2bin.zip / Lib / py_compile.py < prev    next >
Text File  |  1997-11-22  |  994b  |  38 lines

  1. # Routine to "compile" a .py file to a .pyc file.
  2. # This has intimate knowledge of how Python/import.c does it.
  3. # By Sjoerd Mullender (I forced him to write it :-).
  4.  
  5. import imp
  6. MAGIC = imp.get_magic()
  7.  
  8. def wr_long(f, x):
  9.     f.write(chr( x        & 0xff))
  10.     f.write(chr((x >> 8)  & 0xff))
  11.     f.write(chr((x >> 16) & 0xff))
  12.     f.write(chr((x >> 24) & 0xff))
  13.  
  14. def compile(file, cfile = None):
  15.     import os, marshal, __builtin__
  16.     f = open(file)
  17.     try:
  18.         timestamp = os.fstat(file.fileno())
  19.     except AttributeError:
  20.         timestamp = long(os.stat(file)[8])
  21.     codestring = f.read()
  22.     f.close()
  23.     codeobject = __builtin__.compile(codestring, file, 'exec')
  24.     if not cfile:
  25.         cfile = file + (__debug__ and 'c' or 'o')
  26.     fc = open(cfile, 'wb')
  27.     fc.write('\0\0\0\0')
  28.     wr_long(fc, timestamp)
  29.     marshal.dump(codeobject, fc)
  30.     fc.flush()
  31.     fc.seek(0, 0)
  32.     fc.write(MAGIC)
  33.     fc.close()
  34.     if os.name == 'mac':
  35.         import macfs
  36.         macfs.FSSpec(cfile).SetCreatorType('Pyth', 'PYC ')
  37.         macfs.FSSpec(file).SetCreatorType('Pyth', 'TEXT')
  38.