blob: 10af1bb58eaef1429fa7f35166d10d7214c1f38a [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
Georg Brandl1a3284e2007-12-02 09:40:06 +00006import builtins
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +00007import imp
Fred Drakea96f1a32002-08-21 20:23:22 +00008import marshal
9import os
Guido van Rossum88079f42007-07-15 14:02:52 +000010import re
Fred Drakea96f1a32002-08-21 20:23:22 +000011import sys
12import traceback
13
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +000014MAGIC = imp.get_magic()
Guido van Rossum3bb54481994-08-29 10:52:58 +000015
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000016__all__ = ["compile", "main", "PyCompileError"]
17
18
19class PyCompileError(Exception):
20 """Exception raised when an error occurs while attempting to
21 compile the file.
22
23 To raise this exception, use
24
25 raise PyCompileError(exc_type,exc_value,file[,msg])
26
27 where
Tim Peters2c60f7a2003-01-29 03:49:43 +000028
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000029 exc_type: exception type to be used in error message
30 type name can be accesses as class variable
31 'exc_type_name'
Tim Peters2c60f7a2003-01-29 03:49:43 +000032
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000033 exc_value: exception value to be used in error message
34 can be accesses as class variable 'exc_value'
Tim Peters2c60f7a2003-01-29 03:49:43 +000035
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000036 file: name of file being compiled to be used in error message
37 can be accesses as class variable 'file'
Tim Peters2c60f7a2003-01-29 03:49:43 +000038
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000039 msg: string message to be written as error message
40 If no value is given, a default exception message will be given,
41 consistent with 'standard' py_compile output.
42 message (or default) can be accesses as class variable 'msg'
Tim Peters2c60f7a2003-01-29 03:49:43 +000043
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000044 """
Tim Peters2c60f7a2003-01-29 03:49:43 +000045
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000046 def __init__(self, exc_type, exc_value, file, msg=''):
47 exc_type_name = exc_type.__name__
48 if exc_type is SyntaxError:
49 tbtext = ''.join(traceback.format_exception_only(exc_type, exc_value))
50 errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
51 else:
52 errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
Tim Peters2c60f7a2003-01-29 03:49:43 +000053
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000054 Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)
55
56 self.exc_type_name = exc_type_name
57 self.exc_value = exc_value
58 self.file = file
59 self.msg = msg or errmsg
60
61 def __str__(self):
62 return self.msg
63
Skip Montanaroc62c81e2001-02-12 02:00:42 +000064
Guido van Rossum3bb54481994-08-29 10:52:58 +000065def wr_long(f, x):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000066 """Internal; write a 32-bit int to a file in little-endian order."""
Guido van Rossumd6ca5462007-05-22 01:29:33 +000067 f.write(bytes([x & 0xff,
68 (x >> 8) & 0xff,
69 (x >> 16) & 0xff,
70 (x >> 24) & 0xff]))
Guido van Rossum3bb54481994-08-29 10:52:58 +000071
Guido van Rossum88079f42007-07-15 14:02:52 +000072def read_encoding(file, default):
73 """Read the first two lines of the file looking for coding: xyzzy."""
74 f = open(file, "rb")
75 try:
76 for i in range(2):
77 line = f.readline()
78 if not line:
79 break
Antoine Pitroufd036452008-08-19 17:56:33 +000080 m = re.match(br".*\bcoding:\s*(\S+)\b", line)
Guido van Rossum88079f42007-07-15 14:02:52 +000081 if m:
Christian Heimes8bd14fb2007-11-08 16:34:32 +000082 return m.group(1).decode("ascii")
Guido van Rossum88079f42007-07-15 14:02:52 +000083 return default
84 finally:
85 f.close()
86
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000087def compile(file, cfile=None, dfile=None, doraise=False):
Guido van Rossum63566e21998-01-19 04:01:26 +000088 """Byte-compile one Python source file to Python bytecode.
89
90 Arguments:
91
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000092 file: source filename
93 cfile: target filename; defaults to source with 'c' or 'o' appended
94 ('c' normally, 'o' in optimizing mode, giving .pyc or .pyo)
95 dfile: purported filename; defaults to source (this is the filename
96 that will show up in error messages)
97 doraise: flag indicating whether or not an exception should be
98 raised when a compile error is found. If an exception
99 occurs and this flag is set to False, a string
100 indicating the nature of the exception will be printed,
101 and the function will return to the caller. If an
102 exception occurs and this flag is set to True, a
103 PyCompileError exception will be raised.
Tim Peters2c60f7a2003-01-29 03:49:43 +0000104
Guido van Rossum63566e21998-01-19 04:01:26 +0000105 Note that it isn't necessary to byte-compile Python modules for
106 execution efficiency -- Python itself byte-compiles a module when
107 it is loaded, and if it can, writes out the bytecode to the
108 corresponding .pyc (or .pyo) file.
109
110 However, if a Python installation is shared between users, it is a
111 good idea to byte-compile all modules upon installation, since
112 other users may not be able to write in the source directories,
113 and thus they won't be able to write the .pyc/.pyo file, and then
114 they would be byte-compiling every module each time it is loaded.
115 This can slow down program start-up considerably.
116
117 See compileall.py for a script/module that uses this module to
118 byte-compile all installed files (or all files in selected
119 directories).
120
121 """
Guido van Rossum88079f42007-07-15 14:02:52 +0000122 encoding = read_encoding(file, "utf-8")
Benjamin Peterson32ca4542010-03-18 21:58:43 +0000123 with open(file, encoding=encoding) as f:
124 try:
125 timestamp = int(os.fstat(f.fileno()).st_mtime)
126 except AttributeError:
127 timestamp = int(os.stat(file).st_mtime)
128 codestring = f.read()
Guido van Rossum63566e21998-01-19 04:01:26 +0000129 if codestring and codestring[-1] != '\n':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000130 codestring = codestring + '\n'
Guido van Rossumf984a651998-09-29 15:57:42 +0000131 try:
Georg Brandl1a3284e2007-12-02 09:40:06 +0000132 codeobject = builtins.compile(codestring, dfile or file,'exec')
Guido van Rossumb940e112007-01-10 16:19:56 +0000133 except Exception as err:
Guido van Rossumbd4a63e2007-08-10 17:36:34 +0000134 py_exc = PyCompileError(err.__class__, err, dfile or file)
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000135 if doraise:
136 raise py_exc
137 else:
Georg Brandle537d6e2005-06-10 17:15:18 +0000138 sys.stderr.write(py_exc.msg + '\n')
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000139 return
Raymond Hettinger16e3c422002-06-01 16:07:16 +0000140 if cfile is None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000141 cfile = file + (__debug__ and 'c' or 'o')
Benjamin Peterson32ca4542010-03-18 21:58:43 +0000142 with open(cfile, 'wb') as fc:
143 fc.write(b'\0\0\0\0')
144 wr_long(fc, timestamp)
145 marshal.dump(codeobject, fc)
146 fc.flush()
147 fc.seek(0, 0)
148 fc.write(MAGIC)
Fred Drake61cf4402002-08-21 20:56:21 +0000149
150def main(args=None):
151 """Compile several source files.
152
153 The files named in 'args' (or on the command line, if 'args' is
154 not specified) are compiled and the resulting bytecode is cached
155 in the normal manner. This function does not search a directory
156 structure to locate source files; it only compiles files named
157 explicitly.
158
159 """
160 if args is None:
161 args = sys.argv[1:]
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000162 rv = 0
Fred Drake61cf4402002-08-21 20:56:21 +0000163 for filename in args:
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000164 try:
165 compile(filename, doraise=True)
Guido van Rossumb940e112007-01-10 16:19:56 +0000166 except PyCompileError as err:
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000167 # return value to indicate at least one failure
168 rv = 1
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000169 sys.stderr.write(err.msg)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000170 return rv
Tim Peters2c60f7a2003-01-29 03:49:43 +0000171
Fred Drake61cf4402002-08-21 20:56:21 +0000172if __name__ == "__main__":
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000173 sys.exit(main())