1 """Routine to "compile" a .py file to a .pyc (or .pyo) file.
3 This module has intimate knowledge of the format of .pyc files.
7 MAGIC
= imp
.get_magic()
12 """Internal; write a 32-bit int to a file in little-endian order."""
13 f
.write(chr( x
& 0xff))
14 f
.write(chr((x
>> 8) & 0xff))
15 f
.write(chr((x
>> 16) & 0xff))
16 f
.write(chr((x
>> 24) & 0xff))
18 def compile(file, cfile
=None, dfile
=None):
19 """Byte-compile one Python source file to Python bytecode.
24 cfile: target filename; defaults to source with 'c' or 'o' appended
25 ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo)
26 dfile: purported filename; defaults to source (this is the filename
27 that will show up in error messages)
29 Note that it isn't necessary to byte-compile Python modules for
30 execution efficiency -- Python itself byte-compiles a module when
31 it is loaded, and if it can, writes out the bytecode to the
32 corresponding .pyc (or .pyo) file.
34 However, if a Python installation is shared between users, it is a
35 good idea to byte-compile all modules upon installation, since
36 other users may not be able to write in the source directories,
37 and thus they won't be able to write the .pyc/.pyo file, and then
38 they would be byte-compiling every module each time it is loaded.
39 This can slow down program start-up considerably.
41 See compileall.py for a script/module that uses this module to
42 byte-compile all installed files (or all files in selected
46 import os
, marshal
, __builtin__
49 timestamp
= long(os
.fstat(f
.fileno())[8])
50 except AttributeError:
51 timestamp
= long(os
.stat(file)[8])
53 # If parsing from a string, line breaks are \n (see parsetok.c:tok_nextc)
54 # Replace will return original string if pattern is not found, so
55 # we don't need to check whether it is found first.
56 codestring
= codestring
.replace("\r\n","\n")
57 codestring
= codestring
.replace("\r","\n")
59 if codestring
and codestring
[-1] != '\n':
60 codestring
= codestring
+ '\n'
62 codeobject
= __builtin__
.compile(codestring
, dfile
or file, 'exec')
63 except SyntaxError, detail
:
65 lines
= traceback
.format_exception_only(SyntaxError, detail
)
67 sys
.stderr
.write(line
.replace('File "<string>"',
68 'File "%s"' % (dfile
or file)))
71 cfile
= file + (__debug__
and 'c' or 'o')
72 fc
= open(cfile
, 'wb')
74 wr_long(fc
, timestamp
)
75 marshal
.dump(codeobject
, fc
)
82 macfs
.FSSpec(cfile
).SetCreatorType('Pyth', 'PYC ')