Apparently the code to forestall Tk eating events was too aggressive (Tk user input...
[python/dscho.git] / Lib / py_compile.py
blob48c4afc36239f9ff5b0522956dd08b6bb63234ce
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.
4 """
6 import imp
7 MAGIC = imp.get_magic()
9 __all__ = ["compile"]
11 def wr_long(f, x):
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.
21 Arguments:
23 file: source filename
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
43 directories).
45 """
46 import os, marshal, __builtin__
47 f = open(file)
48 try:
49 timestamp = long(os.fstat(f.fileno())[8])
50 except AttributeError:
51 timestamp = long(os.stat(file)[8])
52 codestring = f.read()
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")
58 f.close()
59 if codestring and codestring[-1] != '\n':
60 codestring = codestring + '\n'
61 try:
62 codeobject = __builtin__.compile(codestring, dfile or file, 'exec')
63 except SyntaxError, detail:
64 import traceback, sys
65 lines = traceback.format_exception_only(SyntaxError, detail)
66 for line in lines:
67 sys.stderr.write(line.replace('File "<string>"',
68 'File "%s"' % (dfile or file)))
69 return
70 if not cfile:
71 cfile = file + (__debug__ and 'c' or 'o')
72 fc = open(cfile, 'wb')
73 fc.write('\0\0\0\0')
74 wr_long(fc, timestamp)
75 marshal.dump(codeobject, fc)
76 fc.flush()
77 fc.seek(0, 0)
78 fc.write(MAGIC)
79 fc.close()
80 if os.name == 'mac':
81 import macfs
82 macfs.FSSpec(cfile).SetCreatorType('Pyth', 'PYC ')