blob: dc1cae98dd928e4c9c7d95f0325342b00597512b [file] [log] [blame]
Guido van Rossum63566e21998-01-19 04:01:26 +00001"""Routine to "compile" a .py file to a .pyc (or .pyo) file.
2
3This module has intimate knowledge of the format of .pyc files.
4"""
Guido van Rossum3bb54481994-08-29 10:52:58 +00005
Fred Drakea96f1a32002-08-21 20:23:22 +00006import __builtin__
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +00007import imp
Fred Drakea96f1a32002-08-21 20:23:22 +00008import marshal
9import os
10import sys
11import traceback
12
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +000013MAGIC = imp.get_magic()
Guido van Rossum3bb54481994-08-29 10:52:58 +000014
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000015__all__ = ["compile", "main", "PyCompileError"]
16
17
18class PyCompileError(Exception):
19 """Exception raised when an error occurs while attempting to
20 compile the file.
21
22 To raise this exception, use
23
24 raise PyCompileError(exc_type,exc_value,file[,msg])
25
26 where
Tim Peters2c60f7a2003-01-29 03:49:43 +000027
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000028 exc_type: exception type to be used in error message
29 type name can be accesses as class variable
30 'exc_type_name'
Tim Peters2c60f7a2003-01-29 03:49:43 +000031
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000032 exc_value: exception value to be used in error message
33 can be accesses as class variable 'exc_value'
Tim Peters2c60f7a2003-01-29 03:49:43 +000034
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000035 file: name of file being compiled to be used in error message
36 can be accesses as class variable 'file'
Tim Peters2c60f7a2003-01-29 03:49:43 +000037
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000038 msg: string message to be written as error message
39 If no value is given, a default exception message will be given,
40 consistent with 'standard' py_compile output.
41 message (or default) can be accesses as class variable 'msg'
Tim Peters2c60f7a2003-01-29 03:49:43 +000042
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000043 """
Tim Peters2c60f7a2003-01-29 03:49:43 +000044
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000045 def __init__(self, exc_type, exc_value, file, msg=''):
46 exc_type_name = exc_type.__name__
47 if exc_type is SyntaxError:
48 tbtext = ''.join(traceback.format_exception_only(exc_type, exc_value))
49 errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
50 else:
51 errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
Tim Peters2c60f7a2003-01-29 03:49:43 +000052
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000053 Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)
54
55 self.exc_type_name = exc_type_name
56 self.exc_value = exc_value
57 self.file = file
58 self.msg = msg or errmsg
59
60 def __str__(self):
61 return self.msg
62
Skip Montanaroc62c81e2001-02-12 02:00:42 +000063
Guido van Rossum3bb54481994-08-29 10:52:58 +000064def wr_long(f, x):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000065 """Internal; write a 32-bit int to a file in little-endian order."""
Guido van Rossum63566e21998-01-19 04:01:26 +000066 f.write(chr( x & 0xff))
67 f.write(chr((x >> 8) & 0xff))
68 f.write(chr((x >> 16) & 0xff))
69 f.write(chr((x >> 24) & 0xff))
Guido van Rossum3bb54481994-08-29 10:52:58 +000070
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000071def compile(file, cfile=None, dfile=None, doraise=False):
Guido van Rossum63566e21998-01-19 04:01:26 +000072 """Byte-compile one Python source file to Python bytecode.
73
74 Arguments:
75
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000076 file: source filename
77 cfile: target filename; defaults to source with 'c' or 'o' appended
78 ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo)
79 dfile: purported filename; defaults to source (this is the filename
80 that will show up in error messages)
81 doraise: flag indicating whether or not an exception should be
82 raised when a compile error is found. If an exception
83 occurs and this flag is set to False, a string
84 indicating the nature of the exception will be printed,
85 and the function will return to the caller. If an
86 exception occurs and this flag is set to True, a
87 PyCompileError exception will be raised.
Tim Peters2c60f7a2003-01-29 03:49:43 +000088
Guido van Rossum63566e21998-01-19 04:01:26 +000089 Note that it isn't necessary to byte-compile Python modules for
90 execution efficiency -- Python itself byte-compiles a module when
91 it is loaded, and if it can, writes out the bytecode to the
92 corresponding .pyc (or .pyo) file.
93
94 However, if a Python installation is shared between users, it is a
95 good idea to byte-compile all modules upon installation, since
96 other users may not be able to write in the source directories,
97 and thus they won't be able to write the .pyc/.pyo file, and then
98 they would be byte-compiling every module each time it is loaded.
99 This can slow down program start-up considerably.
100
101 See compileall.py for a script/module that uses this module to
102 byte-compile all installed files (or all files in selected
103 directories).
104
105 """
Benjamin Petersonf5681392010-03-15 03:02:37 +0000106 with open(file, 'U') as f:
107 try:
108 timestamp = long(os.fstat(f.fileno()).st_mtime)
109 except AttributeError:
110 timestamp = long(os.stat(file).st_mtime)
111 codestring = f.read()
Guido van Rossumf984a651998-09-29 15:57:42 +0000112 try:
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000113 codeobject = __builtin__.compile(codestring, dfile or file,'exec')
114 except Exception,err:
115 py_exc = PyCompileError(err.__class__,err.args,dfile or file)
116 if doraise:
117 raise py_exc
118 else:
Georg Brandle537d6e2005-06-10 17:15:18 +0000119 sys.stderr.write(py_exc.msg + '\n')
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000120 return
Raymond Hettinger16e3c422002-06-01 16:07:16 +0000121 if cfile is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000122 cfile = file + (__debug__ and 'c' or 'o')
Benjamin Petersonf5681392010-03-15 03:02:37 +0000123 with open(cfile, 'wb') as fc:
124 fc.write('\0\0\0\0')
125 wr_long(fc, timestamp)
126 marshal.dump(codeobject, fc)
127 fc.flush()
128 fc.seek(0, 0)
129 fc.write(MAGIC)
Fred Drake61cf4402002-08-21 20:56:21 +0000130
131def main(args=None):
132 """Compile several source files.
133
134 The files named in 'args' (or on the command line, if 'args' is
135 not specified) are compiled and the resulting bytecode is cached
136 in the normal manner. This function does not search a directory
137 structure to locate source files; it only compiles files named
Barry Warsawf7f2d6f2010-03-31 21:07:16 +0000138 explicitly. If '-' is the only parameter in args, the list of
139 files is taken from standard input.
Fred Drake61cf4402002-08-21 20:56:21 +0000140
141 """
142 if args is None:
143 args = sys.argv[1:]
Georg Brandla7bd27f2008-03-06 07:41:16 +0000144 rv = 0
Barry Warsawf7f2d6f2010-03-31 21:07:16 +0000145 if args == ['-']:
146 while True:
147 filename = sys.stdin.readline()
148 if not filename:
149 break
150 filename = filename.rstrip('\n')
151 try:
152 compile(filename, doraise=True)
153 except PyCompileError as error:
154 rv = 1
155 sys.stderr.write("%s\n" % error.msg)
156 except IOError as error:
157 rv = 1
158 sys.stderr.write("%s\n" % error)
159 else:
160 for filename in args:
161 try:
162 compile(filename, doraise=True)
Matthias Klosec166b402010-04-20 19:45:34 +0000163 except PyCompileError as error:
Barry Warsawf7f2d6f2010-03-31 21:07:16 +0000164 # return value to indicate at least one failure
165 rv = 1
166 sys.stderr.write(error.msg)
Georg Brandla7bd27f2008-03-06 07:41:16 +0000167 return rv
Tim Peters2c60f7a2003-01-29 03:49:43 +0000168
Fred Drake61cf4402002-08-21 20:56:21 +0000169if __name__ == "__main__":
Georg Brandla7bd27f2008-03-06 07:41:16 +0000170 sys.exit(main())