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) |
Guido van Rossum | 0b23348 | 1997-11-26 15:44:34 +0000 | [diff] [blame] | 17 | try: |
| 18 | timestamp = os.fstat(file.fileno()) |
| 19 | except AttributeError: |
| 20 | timestamp = long(os.stat(file)[8]) |
Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 21 | codestring = f.read() |
| 22 | f.close() |
Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 23 | codeobject = __builtin__.compile(codestring, file, 'exec') |
| 24 | if not cfile: |
Guido van Rossum | 228b8e8 | 1997-04-02 06:13:34 +0000 | [diff] [blame] | 25 | cfile = file + (__debug__ and 'c' or 'o') |
Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 26 | fc = open(cfile, 'wb') |
Guido van Rossum | 0b23348 | 1997-11-26 15:44:34 +0000 | [diff] [blame] | 27 | fc.write('\0\0\0\0') |
Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 28 | wr_long(fc, timestamp) |
| 29 | marshal.dump(codeobject, fc) |
Guido van Rossum | 0b23348 | 1997-11-26 15:44:34 +0000 | [diff] [blame] | 30 | fc.flush() |
| 31 | fc.seek(0, 0) |
| 32 | fc.write(MAGIC) |
Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 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') |