blob: 49306d9dabbc51437d2e5d066633a7c4795d2a42 [file] [log] [blame]
Brett Cannonf299abd2015-04-13 14:21:02 -04001"""Module/script to byte-compile all .py files to .pyc files.
Guido van Rossumc567b811998-01-19 23:07:55 +00002
3When called as a script with arguments, this compiles the directories
4given as arguments recursively; the -l option prevents it from
5recursing into directories.
6
7Without arguments, if compiles all modules on sys.path, without
8recursing into subdirectories. (Even though it should do so for
9packages -- for now, you'll have to deal with packages separately.)
10
11See module py_compile for details of the actual byte-compilation.
Guido van Rossumc567b811998-01-19 23:07:55 +000012"""
Guido van Rossum3bb54481994-08-29 10:52:58 +000013import os
14import sys
Brett Cannon7822e122013-06-14 23:04:02 -040015import importlib.util
Guido van Rossum3bb54481994-08-29 10:52:58 +000016import py_compile
Brett Cannonbefb14f2009-02-10 02:10:16 +000017import struct
Guido van Rossum3bb54481994-08-29 10:52:58 +000018
Brett Cannonf1a8df02014-09-12 10:39:48 -040019from functools import partial
20
Matthias Klosec33b9022010-03-16 00:36:26 +000021__all__ = ["compile_dir","compile_file","compile_path"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000022
Berker Peksag6554b862014-10-15 11:10:57 +030023def _walk_dir(dir, ddir=None, maxlevels=10, quiet=0):
Berker Peksag812a2b62016-10-01 00:54:18 +030024 if quiet < 2 and isinstance(dir, os.PathLike):
25 dir = os.fspath(dir)
Brett Cannonf1a8df02014-09-12 10:39:48 -040026 if not quiet:
27 print('Listing {!r}...'.format(dir))
28 try:
29 names = os.listdir(dir)
30 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +030031 if quiet < 2:
32 print("Can't list {!r}".format(dir))
Brett Cannonf1a8df02014-09-12 10:39:48 -040033 names = []
34 names.sort()
35 for name in names:
36 if name == '__pycache__':
37 continue
38 fullname = os.path.join(dir, name)
39 if ddir is not None:
40 dfile = os.path.join(ddir, name)
41 else:
42 dfile = None
43 if not os.path.isdir(fullname):
44 yield fullname
45 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
46 os.path.isdir(fullname) and not os.path.islink(fullname)):
47 yield from _walk_dir(fullname, ddir=dfile,
48 maxlevels=maxlevels - 1, quiet=quiet)
49
Georg Brandl8334fd92010-12-04 10:26:46 +000050def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080051 quiet=0, legacy=False, optimize=-1, workers=1,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -040052 invalidation_mode=None):
Guido van Rossumc567b811998-01-19 23:07:55 +000053 """Byte-compile all modules in the given directory tree.
Guido van Rossum3bb54481994-08-29 10:52:58 +000054
Guido van Rossumc567b811998-01-19 23:07:55 +000055 Arguments (only dir is required):
56
57 dir: the directory to byte-compile
58 maxlevels: maximum recursion level (default 10)
R. David Murray94f58c32010-12-17 16:29:07 +000059 ddir: the directory that will be prepended to the path to the
60 file as it is compiled into each byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +000061 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +030062 quiet: full output with False or 0, errors only with 1,
63 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +000064 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +000065 optimize: optimization level or -1 for level of the interpreter
Brett Cannonf1a8df02014-09-12 10:39:48 -040066 workers: maximum number of parallel workers
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080067 invalidation_mode: how the up-to-dateness of the pyc will be checked
Guido van Rossumc567b811998-01-19 23:07:55 +000068 """
Dustin Spicuzza1d817e42018-11-23 12:06:55 -050069 ProcessPoolExecutor = None
Antoine Pitrou1a2dd822019-05-15 23:45:18 +020070 if workers < 0:
71 raise ValueError('workers must be greater or equal to 0')
72 if workers != 1:
73 try:
74 # Only import when needed, as low resource platforms may
75 # fail to import it
76 from concurrent.futures import ProcessPoolExecutor
77 except ImportError:
78 workers = 1
Brett Cannonf1a8df02014-09-12 10:39:48 -040079 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
80 ddir=ddir)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080081 success = True
Antoine Pitrou1a2dd822019-05-15 23:45:18 +020082 if workers != 1 and ProcessPoolExecutor is not None:
83 # If workers == 0, let ProcessPoolExecutor choose
Brett Cannonf1a8df02014-09-12 10:39:48 -040084 workers = workers or None
85 with ProcessPoolExecutor(max_workers=workers) as executor:
86 results = executor.map(partial(compile_file,
87 ddir=ddir, force=force,
88 rx=rx, quiet=quiet,
89 legacy=legacy,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080090 optimize=optimize,
91 invalidation_mode=invalidation_mode),
Brett Cannonf1a8df02014-09-12 10:39:48 -040092 files)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080093 success = min(results, default=True)
Brett Cannonf1a8df02014-09-12 10:39:48 -040094 else:
95 for file in files:
96 if not compile_file(file, ddir, force, rx, quiet,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080097 legacy, optimize, invalidation_mode):
Brett Cannon1e3c3e92015-12-27 13:17:04 -080098 success = False
Fred Drake9065ea31999-03-29 20:25:40 +000099 return success
Guido van Rossumc567b811998-01-19 23:07:55 +0000100
Berker Peksag6554b862014-10-15 11:10:57 +0300101def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800102 legacy=False, optimize=-1,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400103 invalidation_mode=None):
Éric Araujo413d7b42010-12-23 18:44:31 +0000104 """Byte-compile one file.
105
106 Arguments (only fullname is required):
107
Barry Warsaw28a691b2010-04-17 00:19:56 +0000108 fullname: the file to byte-compile
R. David Murray94f58c32010-12-17 16:29:07 +0000109 ddir: if given, the directory name compiled in to the
110 byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000111 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +0300112 quiet: full output with False or 0, errors only with 1,
113 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +0000114 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +0000115 optimize: optimization level or -1 for level of the interpreter
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800116 invalidation_mode: how the up-to-dateness of the pyc will be checked
Matthias Klosec33b9022010-03-16 00:36:26 +0000117 """
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800118 success = True
Berker Peksag812a2b62016-10-01 00:54:18 +0300119 if quiet < 2 and isinstance(fullname, os.PathLike):
120 fullname = os.fspath(fullname)
Matthias Klosec33b9022010-03-16 00:36:26 +0000121 name = os.path.basename(fullname)
122 if ddir is not None:
123 dfile = os.path.join(ddir, name)
124 else:
125 dfile = None
126 if rx is not None:
127 mo = rx.search(fullname)
128 if mo:
129 return success
130 if os.path.isfile(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000131 if legacy:
Brett Cannonf299abd2015-04-13 14:21:02 -0400132 cfile = fullname + 'c'
Barry Warsaw28a691b2010-04-17 00:19:56 +0000133 else:
Georg Brandl8334fd92010-12-04 10:26:46 +0000134 if optimize >= 0:
Brett Cannonf299abd2015-04-13 14:21:02 -0400135 opt = optimize if optimize >= 1 else ''
Brett Cannon7822e122013-06-14 23:04:02 -0400136 cfile = importlib.util.cache_from_source(
Brett Cannonf299abd2015-04-13 14:21:02 -0400137 fullname, optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000138 else:
Brett Cannon7822e122013-06-14 23:04:02 -0400139 cfile = importlib.util.cache_from_source(fullname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000140 cache_dir = os.path.dirname(cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +0000141 head, tail = name[:-3], name[-3:]
142 if tail == '.py':
143 if not force:
144 try:
145 mtime = int(os.stat(fullname).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800146 expect = struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
147 0, mtime)
Matthias Klosec33b9022010-03-16 00:36:26 +0000148 with open(cfile, 'rb') as chandle:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800149 actual = chandle.read(12)
Matthias Klosec33b9022010-03-16 00:36:26 +0000150 if expect == actual:
151 return success
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200152 except OSError:
Matthias Klosec33b9022010-03-16 00:36:26 +0000153 pass
154 if not quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200155 print('Compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000156 try:
Georg Brandl8334fd92010-12-04 10:26:46 +0000157 ok = py_compile.compile(fullname, cfile, dfile, True,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800158 optimize=optimize,
159 invalidation_mode=invalidation_mode)
Matthias Klosec33b9022010-03-16 00:36:26 +0000160 except py_compile.PyCompileError as err:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800161 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300162 if quiet >= 2:
163 return success
164 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200165 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000166 else:
167 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000168 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000169 msg = err.msg.encode(sys.stdout.encoding,
170 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000171 msg = msg.decode(sys.stdout.encoding)
172 print(msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200173 except (SyntaxError, UnicodeError, OSError) as e:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800174 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300175 if quiet >= 2:
176 return success
177 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200178 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000179 else:
180 print('*** ', end='')
181 print(e.__class__.__name__ + ':', e)
Matthias Klosec33b9022010-03-16 00:36:26 +0000182 else:
183 if ok == 0:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800184 success = False
Matthias Klosec33b9022010-03-16 00:36:26 +0000185 return success
186
Berker Peksag6554b862014-10-15 11:10:57 +0300187def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800188 legacy=False, optimize=-1,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400189 invalidation_mode=None):
Guido van Rossumc567b811998-01-19 23:07:55 +0000190 """Byte-compile all module on sys.path.
191
192 Arguments (all optional):
193
Éric Araujo3b371cf2011-09-01 20:00:33 +0200194 skip_curdir: if true, skip current directory (default True)
Guido van Rossumc567b811998-01-19 23:07:55 +0000195 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000196 force: as for compile_dir() (default False)
Berker Peksag6554b862014-10-15 11:10:57 +0300197 quiet: as for compile_dir() (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000198 legacy: as for compile_dir() (default False)
Georg Brandl8334fd92010-12-04 10:26:46 +0000199 optimize: as for compile_dir() (default -1)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800200 invalidation_mode: as for compiler_dir()
Guido van Rossumc567b811998-01-19 23:07:55 +0000201 """
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800202 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000203 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 if (not dir or dir == os.curdir) and skip_curdir:
Berker Peksag6554b862014-10-15 11:10:57 +0300205 if quiet < 2:
206 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000207 else:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800208 success = success and compile_dir(
209 dir,
210 maxlevels,
211 None,
212 force,
213 quiet=quiet,
214 legacy=legacy,
215 optimize=optimize,
216 invalidation_mode=invalidation_mode,
217 )
Fred Drake9065ea31999-03-29 20:25:40 +0000218 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000219
Matthias Klosec33b9022010-03-16 00:36:26 +0000220
Guido van Rossum3bb54481994-08-29 10:52:58 +0000221def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000222 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000223 import argparse
224
225 parser = argparse.ArgumentParser(
226 description='Utilities to support installing Python libraries.')
R. David Murray94f58c32010-12-17 16:29:07 +0000227 parser.add_argument('-l', action='store_const', const=0,
228 default=10, dest='maxlevels',
229 help="don't recurse into subdirectories")
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500230 parser.add_argument('-r', type=int, dest='recursion',
231 help=('control the maximum recursion level. '
232 'if `-l` and `-r` options are specified, '
233 'then `-r` takes precedence.'))
R. David Murray650f1472010-11-20 21:18:51 +0000234 parser.add_argument('-f', action='store_true', dest='force',
235 help='force rebuild even if timestamps are up to date')
Berker Peksag6554b862014-10-15 11:10:57 +0300236 parser.add_argument('-q', action='count', dest='quiet', default=0,
237 help='output only error messages; -qq will suppress '
238 'the error messages as well.')
R. David Murray650f1472010-11-20 21:18:51 +0000239 parser.add_argument('-b', action='store_true', dest='legacy',
R. David Murray94f58c32010-12-17 16:29:07 +0000240 help='use legacy (pre-PEP3147) compiled file locations')
R. David Murray650f1472010-11-20 21:18:51 +0000241 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
R. David Murray94f58c32010-12-17 16:29:07 +0000242 help=('directory to prepend to file paths for use in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200243 'compile-time tracebacks and in runtime '
R. David Murray94f58c32010-12-17 16:29:07 +0000244 'tracebacks in cases where the source file is '
245 'unavailable'))
R. David Murray650f1472010-11-20 21:18:51 +0000246 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
Éric Araujo3b371cf2011-09-01 20:00:33 +0200247 help=('skip files matching the regular expression; '
248 'the regexp is searched for in the full path '
249 'of each file considered for compilation'))
R. David Murray650f1472010-11-20 21:18:51 +0000250 parser.add_argument('-i', metavar='FILE', dest='flist',
R. David Murray94f58c32010-12-17 16:29:07 +0000251 help=('add all the files and directories listed in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200252 'FILE to the list considered for compilation; '
253 'if "-", names are read from stdin'))
R. David Murray94f58c32010-12-17 16:29:07 +0000254 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
255 help=('zero or more file and directory names '
256 'to compile; if no arguments given, defaults '
257 'to the equivalent of -l sys.path'))
Brett Cannonf1a8df02014-09-12 10:39:48 -0400258 parser.add_argument('-j', '--workers', default=1,
259 type=int, help='Run compileall concurrently')
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800260 invalidation_modes = [mode.name.lower().replace('_', '-')
261 for mode in py_compile.PycInvalidationMode]
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400262 parser.add_argument('--invalidation-mode',
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800263 choices=sorted(invalidation_modes),
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400264 help=('set .pyc invalidation mode; defaults to '
265 '"checked-hash" if the SOURCE_DATE_EPOCH '
266 'environment variable is set, and '
267 '"timestamp" otherwise.'))
R. David Murray650f1472010-11-20 21:18:51 +0000268
Brett Cannonf1a8df02014-09-12 10:39:48 -0400269 args = parser.parse_args()
R. David Murray95333e32010-12-14 22:32:50 +0000270 compile_dests = args.compile_dest
271
R. David Murray650f1472010-11-20 21:18:51 +0000272 if args.rx:
273 import re
274 args.rx = re.compile(args.rx)
275
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500276
277 if args.recursion is not None:
278 maxlevels = args.recursion
279 else:
280 maxlevels = args.maxlevels
281
R. David Murray650f1472010-11-20 21:18:51 +0000282 # if flist is provided then load it
R. David Murray650f1472010-11-20 21:18:51 +0000283 if args.flist:
R. David Murray95333e32010-12-14 22:32:50 +0000284 try:
285 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
286 for line in f:
287 compile_dests.append(line.strip())
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200288 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +0300289 if args.quiet < 2:
290 print("Error reading file list {}".format(args.flist))
R. David Murray95333e32010-12-14 22:32:50 +0000291 return False
R. David Murray650f1472010-11-20 21:18:51 +0000292
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400293 if args.invalidation_mode:
294 ivl_mode = args.invalidation_mode.replace('-', '_').upper()
295 invalidation_mode = py_compile.PycInvalidationMode[ivl_mode]
296 else:
297 invalidation_mode = None
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800298
R. David Murray95333e32010-12-14 22:32:50 +0000299 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000300 try:
R. David Murray650f1472010-11-20 21:18:51 +0000301 if compile_dests:
302 for dest in compile_dests:
R. David Murray5317e9c2010-12-16 19:08:51 +0000303 if os.path.isfile(dest):
304 if not compile_file(dest, args.ddir, args.force, args.rx,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800305 args.quiet, args.legacy,
306 invalidation_mode=invalidation_mode):
R. David Murray5317e9c2010-12-16 19:08:51 +0000307 success = False
308 else:
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500309 if not compile_dir(dest, maxlevels, args.ddir,
R. David Murray650f1472010-11-20 21:18:51 +0000310 args.force, args.rx, args.quiet,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800311 args.legacy, workers=args.workers,
312 invalidation_mode=invalidation_mode):
R. David Murray95333e32010-12-14 22:32:50 +0000313 success = False
R. David Murray95333e32010-12-14 22:32:50 +0000314 return success
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000315 else:
R David Murray8a1d1e62013-12-15 20:49:38 -0500316 return compile_path(legacy=args.legacy, force=args.force,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800317 quiet=args.quiet,
318 invalidation_mode=invalidation_mode)
Guido van Rossumc567b811998-01-19 23:07:55 +0000319 except KeyboardInterrupt:
Berker Peksag6554b862014-10-15 11:10:57 +0300320 if args.quiet < 2:
321 print("\n[interrupted]")
R. David Murray95333e32010-12-14 22:32:50 +0000322 return False
323 return True
R. David Murray650f1472010-11-20 21:18:51 +0000324
Guido van Rossum3bb54481994-08-29 10:52:58 +0000325
326if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000327 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000328 sys.exit(exit_status)