blob: a0f4defdce68c9e719a3a8a64ee53305a20fa052 [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 """
Brett Cannon14581d52013-01-26 08:48:36 -0500115 if cfile is None:
116 if optimize >= 0:
Brett Cannonf299abd2015-04-13 14:21:02 -0400117 optimization = optimize if optimize >= 1 else ''
Brett Cannondf960682013-06-15 14:07:21 -0400118 cfile = importlib.util.cache_from_source(file,
Brett Cannonf299abd2015-04-13 14:21:02 -0400119 optimization=optimization)
Brett Cannon14581d52013-01-26 08:48:36 -0500120 else:
Brett Cannondf960682013-06-15 14:07:21 -0400121 cfile = importlib.util.cache_from_source(file)
Brett Cannon33915eb2013-06-14 18:33:00 -0400122 if os.path.islink(cfile):
123 msg = ('{} is a symlink and will be changed into a regular file if '
124 'import writes a byte-compiled file to it')
Brett Cannon9674bd02013-06-17 17:48:30 -0400125 raise FileExistsError(msg.format(cfile))
Brett Cannon33915eb2013-06-14 18:33:00 -0400126 elif os.path.exists(cfile) and not os.path.isfile(cfile):
127 msg = ('{} is a non-regular file and will be changed into a regular '
128 'one if import writes a byte-compiled file to it')
Brett Cannon9674bd02013-06-17 17:48:30 -0400129 raise FileExistsError(msg.format(cfile))
Brett Cannon14581d52013-01-26 08:48:36 -0500130 loader = importlib.machinery.SourceFileLoader('<py_compile>', file)
131 source_bytes = loader.get_data(file)
Guido van Rossumf984a651998-09-29 15:57:42 +0000132 try:
Brett Cannon14581d52013-01-26 08:48:36 -0500133 code = loader.source_to_code(source_bytes, dfile or file,
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400134 _optimize=optimize)
Guido van Rossumb940e112007-01-10 16:19:56 +0000135 except Exception as err:
Guido van Rossumbd4a63e2007-08-10 17:36:34 +0000136 py_exc = PyCompileError(err.__class__, err, dfile or file)
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000137 if doraise:
138 raise py_exc
139 else:
Georg Brandle537d6e2005-06-10 17:15:18 +0000140 sys.stderr.write(py_exc.msg + '\n')
Martin v. Löwis0c6774d2003-01-15 11:51:06 +0000141 return
Benjamin Peterson25216ba2010-05-08 19:52:21 +0000142 try:
Meador Inge22b9b372011-11-28 09:27:32 -0600143 dirname = os.path.dirname(cfile)
144 if dirname:
145 os.makedirs(dirname)
Brett Cannon14581d52013-01-26 08:48:36 -0500146 except FileExistsError:
147 pass
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800148 if invalidation_mode == PycInvalidationMode.TIMESTAMP:
149 source_stats = loader.path_stats(file)
150 bytecode = importlib._bootstrap_external._code_to_timestamp_pyc(
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400151 code, source_stats['mtime'], source_stats['size'])
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800152 else:
153 source_hash = importlib.util.source_hash(source_bytes)
154 bytecode = importlib._bootstrap_external._code_to_hash_pyc(
155 code,
156 source_hash,
157 (invalidation_mode == PycInvalidationMode.CHECKED_HASH),
158 )
Eric Snow32439d62015-05-02 19:15:18 -0600159 mode = importlib._bootstrap_external._calc_mode(file)
160 importlib._bootstrap_external._write_atomic(cfile, bytecode, mode)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000161 return cfile
Fred Drake61cf4402002-08-21 20:56:21 +0000162
Brett Cannonedfd6ae2013-04-14 12:48:15 -0400163
Fred Drake61cf4402002-08-21 20:56:21 +0000164def main(args=None):
165 """Compile several source files.
166
167 The files named in 'args' (or on the command line, if 'args' is
168 not specified) are compiled and the resulting bytecode is cached
169 in the normal manner. This function does not search a directory
170 structure to locate source files; it only compiles files named
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000171 explicitly. If '-' is the only parameter in args, the list of
172 files is taken from standard input.
Fred Drake61cf4402002-08-21 20:56:21 +0000173
174 """
175 if args is None:
176 args = sys.argv[1:]
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000177 rv = 0
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000178 if args == ['-']:
179 while True:
180 filename = sys.stdin.readline()
181 if not filename:
182 break
183 filename = filename.rstrip('\n')
184 try:
185 compile(filename, doraise=True)
186 except PyCompileError as error:
187 rv = 1
188 sys.stderr.write("%s\n" % error.msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200189 except OSError as error:
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000190 rv = 1
191 sys.stderr.write("%s\n" % error)
192 else:
193 for filename in args:
194 try:
195 compile(filename, doraise=True)
Matthias Klose1c994732010-04-20 19:48:04 +0000196 except PyCompileError as error:
Barry Warsawd5f9bf52010-03-31 21:36:22 +0000197 # return value to indicate at least one failure
198 rv = 1
Berker Peksag34c9be72015-04-14 18:57:55 +0300199 sys.stderr.write("%s\n" % error.msg)
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000200 return rv
Tim Peters2c60f7a2003-01-29 03:49:43 +0000201
Fred Drake61cf4402002-08-21 20:56:21 +0000202if __name__ == "__main__":
Christian Heimesdd15f6c2008-03-16 00:07:10 +0000203 sys.exit(main())