Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 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 | codestring = f.read() |
| 18 | f.close() |
Guido van Rossum | c45289c | 1996-10-24 22:27:16 +0000 | [diff] [blame] | 19 | timestamp = long(os.stat(file)[8]) |
Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 20 | codeobject = __builtin__.compile(codestring, file, 'exec') |
| 21 | if not cfile: |
| 22 | cfile = file + 'c' |
| 23 | fc = open(cfile, 'wb') |
| 24 | fc.write(MAGIC) |
| 25 | wr_long(fc, timestamp) |
| 26 | marshal.dump(codeobject, fc) |
| 27 | fc.close() |
| 28 | if os.name == 'mac': |
| 29 | import macfs |
| 30 | macfs.FSSpec(cfile).SetCreatorType('Pyth', 'PYC ') |
| 31 | macfs.FSSpec(file).SetCreatorType('Pyth', 'TEXT') |