Guido van Rossum | 3bb5448 | 1994-08-29 10:52:58 +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 | MAGIC = 0x999903 |
| 6 | |
| 7 | def wr_long(f, x): |
| 8 | f.write(chr( x & 0xff)) |
| 9 | f.write(chr((x >> 8) & 0xff)) |
| 10 | f.write(chr((x >> 16) & 0xff)) |
| 11 | f.write(chr((x >> 24) & 0xff)) |
| 12 | |
| 13 | def compile(file, cfile = None): |
| 14 | import os, marshal, __builtin__ |
| 15 | f = open(file) |
| 16 | codestring = f.read() |
| 17 | timestamp = os.fstat(f.fileno())[8] |
| 18 | f.close() |
| 19 | codeobject = __builtin__.compile(codestring, file, 'exec') |
| 20 | if not cfile: |
| 21 | cfile = file + 'c' |
| 22 | fc = open(cfile, 'w') |
| 23 | wr_long(fc, MAGIC) |
| 24 | wr_long(fc, timestamp) |
| 25 | marshal.dump(codeobject, fc) |