blob: 16dc0a011ffab2a8fe58bac8a8c956add95d76bb [file] [log] [blame]
Brett Cannonf299abd2015-04-13 14:21:02 -04001"""Routine to "compile" a .py file to a .pyc file.
Guido van Rossum63566e21998-01-19 04:01:26 +00002
3This module has intimate knowledge of the format of .pyc files.
4"""
Guido van Rossum3bb54481994-08-29 10:52:58 +00005
Benjamin Peterson42aa93b2017-12-09 10:26:52 -08006import enum
Eric Snow32439d62015-05-02 19:15:18 -06007import importlib._bootstrap_external
Brett Cannon14581d52013-01-26 08:48:36 -05008import importlib.machinery
Brett Cannondf960682013-06-15 14:07:21 -04009import importlib.util
Fred Drakea96f1a32002-08-21 20:23:22 +000010import os
Brett Cannon33915eb2013-06-14 18:33:00 -040011import os.path
Fred Drakea96f1a32002-08-21 20:23:22 +000012import sys
13import traceback
14
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080015__all__ = ["compile", "main", "PyCompileError", "PycInvalidationMode"]
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000016
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
Barry Warsaw28a691b2010-04-17 00:19:56 +000039 If no value is given, a default exception message will be
40 given, consistent with 'standard' py_compile output.
41 message (or default) can be accesses as class variable
42 '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:
Barry Warsaw28a691b2010-04-17 00:19:56 +000049 tbtext = ''.join(traceback.format_exception_only(
50 exc_type, exc_value))
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000051 errmsg = tbtext.replace('File "<string>"', 'File "%s"' % file)
52 else:
53 errmsg = "Sorry: %s: %s" % (exc_type_name,exc_value)
Tim Peters2c60f7a2003-01-29 03:49:43 +000054
Martin v. Löwis0c6774d2003-01-15 11:51:06 +000055 Exception.__init__(self,msg or errmsg,exc_type_name,exc_value,file)
56
57 self.exc_type_name = exc_type_name
58 self.exc_value = exc_value
59 self.file = file
60 self.msg = msg or errmsg
61
62 def __str__(self):
63 return self.msg
64
Skip Montanaroc62c81e2001-02-12 02:00:42 +000065
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080066class PycInvalidationMode(enum.Enum):
67 TIMESTAMP = 1
68 CHECKED_HASH = 2
69 UNCHECKED_HASH = 3
70
71
72def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1,
73 invalidation_mode=PycInvalidationMode.TIMESTAMP):
Guido van Rossum63566e21998-01-19 04:01:26 +000074 """Byte-compile one Python source file to Python bytecode.
75
Barry Warsaw28a691b2010-04-17 00:19:56 +000076 :param file: The source file name.
77 :param cfile: The target byte compiled file name. When not given, this
Brett Cannonf299abd2015-04-13 14:21:02 -040078 defaults to the PEP 3147/PEP 488 location.
Barry Warsaw28a691b2010-04-17 00:19:56 +000079 :param dfile: Purported file name, i.e. the file name that shows up in
80 error messages. Defaults to the source file name.
81 :param doraise: Flag indicating whether or not an exception should be
82 raised when a compile error is found. If an exception occurs and this
83 flag is set to False, a string indicating the nature of the exception
84 will be printed, and the function will return to the caller. If an
85 exception occurs and this flag is set to True, a PyCompileError
86 exception will be raised.
Georg Brandl8334fd92010-12-04 10:26:46 +000087 :param optimize: The optimization level for the compiler. Valid values
88 are -1, 0, 1 and 2. A value of -1 means to use the optimization
89 level of the current interpreter, as given by -O command line options.
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080090 :param invalidation_mode:
Georg Brandl8334fd92010-12-04 10:26:46 +000091
Barry Warsaw28a691b2010-04-17 00:19:56 +000092 :return: Path to the resulting byte compiled file.
Tim Peters2c60f7a2003-01-29 03:49:43 +000093
Guido van Rossum63566e21998-01-19 04:01:26 +000094 Note that it isn't necessary to byte-compile Python modules for
95 execution efficiency -- Python itself byte-compiles a module when
96 it is loaded, and if it can, writes out the bytecode to the
Brett Cannonf299abd2015-04-13 14:21:02 -040097 corresponding .pyc file.
Guido van Rossum63566e21998-01-19 04:01:26 +000098
99 However, if a Python installation is shared between users, it is a
100 good idea to byte-compile all modules upon installation, since
101 other users may not be able to write in the source directories,
Brett Cannonf299abd2015-04-13 14:21:02 -0400102 and thus they won't be able to write the .pyc file, and then
Guido van Rossum63566e21998-01-19 04:01:26 +0000103 they would be byte-compiling every module each time it is loaded.
104 This can slow down program start-up considerably.
105
106 See compileall.py for a script/module that uses this module to
107 byte-compile all installed files (or all files in selected
108 directories).
Brett Cannon33915eb2013-06-14 18:33:00 -0400109
110 Do note that FileExistsError is raised if cfile ends up pointing at a
111 non-regular file or symlink. Because the compilation uses a file renaming,
112 the resulting file would be regular and thus not the same type of file as
113 it was previously.
Guido van Rossum63566e21998-01-19 04:01:26 +0000114 """
Bernhard M. Wiedemannccbe5812018-01-24 22:26:18 +0100115 if os.environ.get('SOURCE_DATE_EPOCH'):
116 invalidation_mode = PycInvalidationMode.CHECKED_HASH
Brett Cannon14581d52013-01-26 08:48:36 -0500117 if cfile is None:
118 if optimize >= 0:
Brett Cannonf299abd2015-04-13 14:21:02 -0400119 optimization = optimize if optimize >= 1 else ''
Brett Cannondf960682013-06-15 14:07:21 -0400120 cfile = importlib.util.cache_from_source(file,
Brett Cannonf299abd2015-04-13 14:21:02 -0400121 optimization=optimization)
Brett Cannon14581d52013-01-26 08:48:36 -0500122 else:
Brett Cannondf960682013-06-15 14:07:21 -0400123 cfile = importlib.util.cache_from_source(file)
Brett Cannon33915eb2013-06-14 18:33:00 -0400124 if os.path.islink(cfile):
125 msg = ('{} is a symlink and will be changed into a regular file if '
126 'import writes a byte-compiled file to it')
Brett Cannon9674bd02013-06-17 17:48:30 -0400127 raise FileExistsError(msg.format(cfile))
Brett Cannon33915eb2013-06-14 18:33:00 -0400128 elif os.path.exists(cfile) and not os.path.isfile(cfile):
129 msg = ('{} is a non-regular file and will be changed into a regular '
130 'one if import writes a byte-compiled file to it')
Brett Cannon9674bd02013-06-17 17:48:30 -0400131 raise FileExistsError(msg.format(cfile))
Brett Cannon14581d52013-01-26 08:48:36 -0500132 loader = importlib.machinery.SourceFileLoader('<py_compile>', file)
133 source_bytes = loader.get_data(file)
Guido van Rossumf984a651998-09-29 15:57:42 +0000134 try:
Brett Cannon14581d52013-01-26 08:48:36 -0500135 code = loader.source_to_code(source_bytes, dfile or file,
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400136 _optimize=optimize)
Guido van Rossumb940e112007-01-10 16:19:56 +0000137 except Exception as err:
Guido van Rossumbd4a63e2007-08-10 17:36:34 +0000138 py_exc = PyCompileError(err.__class__, err, dfile or file)
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000139 if doraise:
140 raise py_exc
141 else:
Georg Brandle537d6e2005-06-10 17:15:18 +0000142 sys.stderr.write(py_exc.msg + '\n')
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000143 return
Benjamin Peterson25216ba2010-05-08 19:52:21 +0000144 try:
Meador Inge22b9b372011-11-28 09:27:32 -0600145 dirname = os.path.dirname(cfile)
146 if dirname:
147 os.makedirs(dirname)
Brett Cannon14581d52013-01-26 08:48:36 -0500148 except FileExistsError:
149 pass
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800150 if invalidation_mode == PycInvalidationMode.TIMESTAMP:
151 source_stats = loader.path_stats(file)
152 bytecode = importlib._bootstrap_external._code_to_timestamp_pyc(
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400153 code, source_stats['mtime'], source_stats['size'])
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800154 else:
155 source_hash = importlib.util.source_hash(source_bytes)
156 bytecode = importlib._bootstrap_external._code_to_hash_pyc(
157 code,
158 source_hash,
159 (invalidation_mode == PycInvalidationMode.CHECKED_HASH),
160 )
Eric Snow32439d62015-05-02 19:15:18 -0600161 mode = importlib._bootstrap_external._calc_mode(file)
162 importlib._bootstrap_external._write_atomic(cfile, bytecode, mode)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000163 return cfile
Fred Drake61cf4402002-08-21 20:56:21 +0000164
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400165
Fred Drake61cf4402002-08-21 20:56:21 +0000166def main(args=None):
167 """Compile several source files.
168
169 The files named in 'args' (or on the command line, if 'args' is
170 not specified) are compiled and the resulting bytecode is cached
171 in the normal manner. This function does not search a directory
172 structure to locate source files; it only compiles files named
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000173 explicitly. If '-' is the only parameter in args, the list of
174 files is taken from standard input.
Fred Drake61cf4402002-08-21 20:56:21 +0000175
176 """
177 if args is None:
178 args = sys.argv[1:]
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000179 rv = 0
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000180 if args == ['-']:
181 while True:
182 filename = sys.stdin.readline()
183 if not filename:
184 break
185 filename = filename.rstrip('\n')
186 try:
187 compile(filename, doraise=True)
188 except PyCompileError as error:
189 rv = 1
190 sys.stderr.write("%s\n" % error.msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200191 except OSError as error:
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000192 rv = 1
193 sys.stderr.write("%s\n" % error)
194 else:
195 for filename in args:
196 try:
197 compile(filename, doraise=True)
Matthias Klose1c994732010-04-20 19:48:04 +0000198 except PyCompileError as error:
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000199 # return value to indicate at least one failure
200 rv = 1
Berker Peksag34c9be72015-04-14 18:57:55 +0300201 sys.stderr.write("%s\n" % error.msg)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000202 return rv
Tim Peters2c60f7a2003-01-29 03:49:43 +0000203
Fred Drake61cf4402002-08-21 20:56:21 +0000204if __name__ == "__main__":
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000205 sys.exit(main())