blob: 1adc3a209c608d7236ccc0aba98d0272e50e1933 [file] [log] [blame]
Guido van Rossum3bb54481994-08-29 10:52:58 +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
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +00005import imp
6MAGIC = imp.get_magic()
Guido van Rossum3bb54481994-08-29 10:52:58 +00007
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 Rossume6c128f1997-11-22 21:48:26 +000017 try:
18 timestamp = os.fstat(file.fileno())
19 except AttributeError:
20 timestamp = long(os.stat(file)[8])
Guido van Rossum3bb54481994-08-29 10:52:58 +000021 codestring = f.read()
Guido van Rossum3bb54481994-08-29 10:52:58 +000022 f.close()
23 codeobject = __builtin__.compile(codestring, file, 'exec')
24 if not cfile:
Fred Drakeef8dc061997-03-13 14:13:16 +000025 cfile = file + (__debug__ and 'c' or 'o')
Guido van Rossum7e4b2de1995-01-27 02:41:45 +000026 fc = open(cfile, 'wb')
Guido van Rossume6c128f1997-11-22 21:48:26 +000027 fc.write('\0\0\0\0')
Guido van Rossum3bb54481994-08-29 10:52:58 +000028 wr_long(fc, timestamp)
29 marshal.dump(codeobject, fc)
Guido van Rossume6c128f1997-11-22 21:48:26 +000030 fc.flush()
31 fc.seek(0, 0)
32 fc.write(MAGIC)
Guido van Rossum7e4b2de1995-01-27 02:41:45 +000033 fc.close()
34 if os.name == 'mac':
Jack Jansene99c8241995-04-23 22:06:57 +000035 import macfs
Guido van Rossumdc42b8a1996-05-28 23:01:05 +000036 macfs.FSSpec(cfile).SetCreatorType('Pyth', 'PYC ')
37 macfs.FSSpec(file).SetCreatorType('Pyth', 'TEXT')