blob: 5adb70a2939fdd247d24f12ee3ba2fc492717506 [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
Barry Warsaw28a691b2010-04-17 00:19:56 +00007import errno
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +00008import imp
Fred Drakea96f1a32002-08-21 20:23:22 +00009import marshal
10import os
11import sys
Benjamin Peterson00888932010-03-18 22:37:38 +000012import tokenize
Fred Drakea96f1a32002-08-21 20:23:22 +000013import traceback
14
Sjoerd Mullender2e5168c1995-07-19 11:21:47 +000015MAGIC = imp.get_magic()
Guido van Rossum3bb54481994-08-29 10:52:58 +000016
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000017__all__ = ["compile", "main", "PyCompileError"]
18
19
20class PyCompileError(Exception):
21 """Exception raised when an error occurs while attempting to
22 compile the file.
23
24 To raise this exception, use
25
26 raise PyCompileError(exc_type,exc_value,file[,msg])
27
28 where
Tim Peters2c60f7a2003-01-29 03:49:43 +000029
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000030 exc_type: exception type to be used in error message
31 type name can be accesses as class variable
32 'exc_type_name'
Tim Peters2c60f7a2003-01-29 03:49:43 +000033
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000034 exc_value: exception value to be used in error message
35 can be accesses as class variable 'exc_value'
Tim Peters2c60f7a2003-01-29 03:49:43 +000036
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000037 file: name of file being compiled to be used in error message
38 can be accesses as class variable 'file'
Tim Peters2c60f7a2003-01-29 03:49:43 +000039
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000040 msg: string message to be written as error message
Barry Warsaw28a691b2010-04-17 00:19:56 +000041 If no value is given, a default exception message will be
42 given, consistent with 'standard' py_compile output.
43 message (or default) can be accesses as class variable
44 'msg'
Tim Peters2c60f7a2003-01-29 03:49:43 +000045
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000046 """
Tim Peters2c60f7a2003-01-29 03:49:43 +000047
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000048 def __init__(self, exc_type, exc_value, file, msg=''):
49 exc_type_name = exc_type.__name__
50 if exc_type is SyntaxError:
Barry Warsaw28a691b2010-04-17 00:19:56 +000051 tbtext = ''.join(traceback.format_exception_only(
52 exc_type, exc_value))
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000053 errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
54 else:
55 errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
Tim Peters2c60f7a2003-01-29 03:49:43 +000056
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000057 Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)
58
59 self.exc_type_name = exc_type_name
60 self.exc_value = exc_value
61 self.file = file
62 self.msg = msg or errmsg
63
64 def __str__(self):
65 return self.msg
66
Skip Montanaroc62c81e2001-02-12 02:00:42 +000067
Guido van Rossum3bb54481994-08-29 10:52:58 +000068def wr_long(f, x):
Guido van Rossum54f22ed2000-02-04 15:10:34 +000069 """Internal; write a 32-bit int to a file in little-endian order."""
Barry Warsaw28a691b2010-04-17 00:19:56 +000070 f.write(bytes([x & 0xff,
Guido van Rossumd6ca5462007-05-22 01:29:33 +000071 (x >> 8) & 0xff,
72 (x >> 16) & 0xff,
73 (x >> 24) & 0xff]))
Guido van Rossum3bb54481994-08-29 10:52:58 +000074
Georg Brandl8334fd92010-12-04 10:26:46 +000075def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1):
Guido van Rossum63566e21998-01-19 04:01:26 +000076 """Byte-compile one Python source file to Python bytecode.
77
Barry Warsaw28a691b2010-04-17 00:19:56 +000078 :param file: The source file name.
79 :param cfile: The target byte compiled file name. When not given, this
80 defaults to the PEP 3147 location.
81 :param dfile: Purported file name, i.e. the file name that shows up in
82 error messages. Defaults to the source file name.
83 :param doraise: Flag indicating whether or not an exception should be
84 raised when a compile error is found. If an exception occurs and this
85 flag is set to False, a string indicating the nature of the exception
86 will be printed, and the function will return to the caller. If an
87 exception occurs and this flag is set to True, a PyCompileError
88 exception will be raised.
Georg Brandl8334fd92010-12-04 10:26:46 +000089 :param optimize: The optimization level for the compiler. Valid values
90 are -1, 0, 1 and 2. A value of -1 means to use the optimization
91 level of the current interpreter, as given by -O command line options.
92
Barry Warsaw28a691b2010-04-17 00:19:56 +000093 :return: Path to the resulting byte compiled file.
Tim Peters2c60f7a2003-01-29 03:49:43 +000094
Guido van Rossum63566e21998-01-19 04:01:26 +000095 Note that it isn't necessary to byte-compile Python modules for
96 execution efficiency -- Python itself byte-compiles a module when
97 it is loaded, and if it can, writes out the bytecode to the
98 corresponding .pyc (or .pyo) file.
99
100 However, if a Python installation is shared between users, it is a
101 good idea to byte-compile all modules upon installation, since
102 other users may not be able to write in the source directories,
103 and thus they won't be able to write the .pyc/.pyo file, and then
104 they would be byte-compiling every module each time it is loaded.
105 This can slow down program start-up considerably.
106
107 See compileall.py for a script/module that uses this module to
108 byte-compile all installed files (or all files in selected
109 directories).
Guido van Rossum63566e21998-01-19 04:01:26 +0000110 """
Victor Stinner58c07522010-11-09 01:08:59 +0000111 with tokenize.open(file) as f:
Benjamin Peterson32ca4542010-03-18 21:58:43 +0000112 try:
113 timestamp = int(os.fstat(f.fileno()).st_mtime)
114 except AttributeError:
115 timestamp = int(os.stat(file).st_mtime)
116 codestring = f.read()
Guido van Rossumf984a651998-09-29 15:57:42 +0000117 try:
Georg Brandl8334fd92010-12-04 10:26:46 +0000118 codeobject = builtins.compile(codestring, dfile or file, 'exec',
119 optimize=optimize)
Guido van Rossumb940e112007-01-10 16:19:56 +0000120 except Exception as err:
Guido van Rossumbd4a63e2007-08-10 17:36:34 +0000121 py_exc = PyCompileError(err.__class__, err, dfile or file)
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000122 if doraise:
123 raise py_exc
124 else:
Georg Brandle537d6e2005-06-10 17:15:18 +0000125 sys.stderr.write(py_exc.msg + '\n')
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000126 return
Raymond Hettinger16e3c422002-06-01 16:07:16 +0000127 if cfile is None:
Georg Brandl8334fd92010-12-04 10:26:46 +0000128 if optimize >= 0:
129 cfile = imp.cache_from_source(file, debug_override=not optimize)
130 else:
131 cfile = imp.cache_from_source(file)
Benjamin Peterson25216ba2010-05-08 19:52:21 +0000132 try:
Meador Inge22b9b372011-11-28 09:27:32 -0600133 dirname = os.path.dirname(cfile)
134 if dirname:
135 os.makedirs(dirname)
Benjamin Peterson25216ba2010-05-08 19:52:21 +0000136 except OSError as error:
137 if error.errno != errno.EEXIST:
138 raise
Benjamin Peterson32ca4542010-03-18 21:58:43 +0000139 with open(cfile, 'wb') as fc:
140 fc.write(b'\0\0\0\0')
141 wr_long(fc, timestamp)
142 marshal.dump(codeobject, fc)
143 fc.flush()
144 fc.seek(0, 0)
145 fc.write(MAGIC)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000146 return cfile
Fred Drake61cf4402002-08-21 20:56:21 +0000147
148def main(args=None):
149 """Compile several source files.
150
151 The files named in 'args' (or on the command line, if 'args' is
152 not specified) are compiled and the resulting bytecode is cached
153 in the normal manner. This function does not search a directory
154 structure to locate source files; it only compiles files named
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000155 explicitly. If '-' is the only parameter in args, the list of
156 files is taken from standard input.
Fred Drake61cf4402002-08-21 20:56:21 +0000157
158 """
159 if args is None:
160 args = sys.argv[1:]
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000161 rv = 0
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000162 if args == ['-']:
163 while True:
164 filename = sys.stdin.readline()
165 if not filename:
166 break
167 filename = filename.rstrip('\n')
168 try:
169 compile(filename, doraise=True)
170 except PyCompileError as error:
171 rv = 1
172 sys.stderr.write("%s\n" % error.msg)
173 except IOError as error:
174 rv = 1
175 sys.stderr.write("%s\n" % error)
176 else:
177 for filename in args:
178 try:
179 compile(filename, doraise=True)
Matthias Klose1c994732010-04-20 19:48:04 +0000180 except PyCompileError as error:
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000181 # return value to indicate at least one failure
182 rv = 1
183 sys.stderr.write(error.msg)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000184 return rv
Tim Peters2c60f7a2003-01-29 03:49:43 +0000185
Fred Drake61cf4402002-08-21 20:56:21 +0000186if __name__ == "__main__":
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000187 sys.exit(main())