blob: e9e90ff6efa159f25db32eace3be0f6c1afaad0c [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)
17 codestring = f.read()
18 f.close()
Guido van Rossumc45289c1996-10-24 22:27:16 +000019 timestamp = long(os.stat(file)[8])
Guido van Rossum5c971671996-07-22 15:23:25 +000020 codeobject = __builtin__.compile(codestring, file, 'exec')
21 if not cfile:
Guido van Rossum228b8e81997-04-02 06:13:34 +000022 cfile = file + (__debug__ and 'c' or 'o')
Guido van Rossum5c971671996-07-22 15:23:25 +000023 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')