blob: 2e68ba82c5b81770eb205b09bbefeb6db82ef183 [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)
17 codestring = f.read()
Guido van Rossum3bb54481994-08-29 10:52:58 +000018 f.close()
Guido van Rossum7e4b2de1995-01-27 02:41:45 +000019 timestamp = os.stat(file)[8]
Guido van Rossum3bb54481994-08-29 10:52:58 +000020 codeobject = __builtin__.compile(codestring, file, 'exec')
21 if not cfile:
22 cfile = file + 'c'
Guido van Rossum7e4b2de1995-01-27 02:41:45 +000023 fc = open(cfile, 'wb')
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +000024 fc.write(MAGIC)
Guido van Rossum3bb54481994-08-29 10:52:58 +000025 wr_long(fc, timestamp)
26 marshal.dump(codeobject, fc)
Guido van Rossum7e4b2de1995-01-27 02:41:45 +000027 fc.close()
28 if os.name == 'mac':
Jack Jansene99c8241995-04-23 22:06:57 +000029 import macfs
Guido van Rossumdc42b8a1996-05-28 23:01:05 +000030 macfs.FSSpec(cfile).SetCreatorType('Pyth', 'PYC ')
31 macfs.FSSpec(file).SetCreatorType('Pyth', 'TEXT')