blob: 1adc3a209c608d7236ccc0aba98d0272e50e1933 [file] [log] [blame]
Guido van Rossum5c971671996-07-22 15:23:25 +00001# 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
5import imp
6MAGIC = imp.get_magic()
7
8def 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
14def compile(file, cfile = None):
15 import os, marshal, __builtin__
16 f = open(file)
Guido van Rossum0b233481997-11-26 15:44:34 +000017 try:
18 timestamp = os.fstat(file.fileno())
19 except AttributeError:
20 timestamp = long(os.stat(file)[8])
Guido van Rossum5c971671996-07-22 15:23:25 +000021 codestring = f.read()
22 f.close()
Guido van Rossum5c971671996-07-22 15:23:25 +000023 codeobject = __builtin__.compile(codestring, file, 'exec')
24 if not cfile:
Guido van Rossum228b8e81997-04-02 06:13:34 +000025 cfile = file + (__debug__ and 'c' or 'o')
Guido van Rossum5c971671996-07-22 15:23:25 +000026 fc = open(cfile, 'wb')
Guido van Rossum0b233481997-11-26 15:44:34 +000027 fc.write('\0\0\0\0')
Guido van Rossum5c971671996-07-22 15:23:25 +000028 wr_long(fc, timestamp)
29 marshal.dump(codeobject, fc)
Guido van Rossum0b233481997-11-26 15:44:34 +000030 fc.flush()
31 fc.seek(0, 0)
32 fc.write(MAGIC)
Guido van Rossum5c971671996-07-22 15:23:25 +000033 fc.close()
34 if os.name == 'mac':
35 import macfs
36 macfs.FSSpec(cfile).SetCreatorType('Pyth', 'PYC ')
37 macfs.FSSpec(file).SetCreatorType('Pyth', 'TEXT')