blob: 72592126d74c3af79642361b174d2210706f5147 [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 -040019try:
20 from concurrent.futures import ProcessPoolExecutor
21except ImportError:
22 ProcessPoolExecutor = None
23from functools import partial
24
Matthias Klosec33b9022010-03-16 00:36:26 +000025__all__ = ["compile_dir","compile_file","compile_path"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000026
Berker Peksag6554b862014-10-15 11:10:57 +030027def _walk_dir(dir, ddir=None, maxlevels=10, quiet=0):
Berker Peksag812a2b62016-10-01 00:54:18 +030028 if quiet < 2 and isinstance(dir, os.PathLike):
29 dir = os.fspath(dir)
Brett Cannonf1a8df02014-09-12 10:39:48 -040030 if not quiet:
31 print('Listing {!r}...'.format(dir))
32 try:
33 names = os.listdir(dir)
34 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +030035 if quiet < 2:
36 print("Can't list {!r}".format(dir))
Brett Cannonf1a8df02014-09-12 10:39:48 -040037 names = []
38 names.sort()
39 for name in names:
40 if name == '__pycache__':
41 continue
42 fullname = os.path.join(dir, name)
43 if ddir is not None:
44 dfile = os.path.join(ddir, name)
45 else:
46 dfile = None
47 if not os.path.isdir(fullname):
48 yield fullname
49 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
50 os.path.isdir(fullname) and not os.path.islink(fullname)):
51 yield from _walk_dir(fullname, ddir=dfile,
52 maxlevels=maxlevels - 1, quiet=quiet)
53
Georg Brandl8334fd92010-12-04 10:26:46 +000054def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080055 quiet=0, legacy=False, optimize=-1, workers=1,
56 invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP):
Guido van Rossumc567b811998-01-19 23:07:55 +000057 """Byte-compile all modules in the given directory tree.
Guido van Rossum3bb54481994-08-29 10:52:58 +000058
Guido van Rossumc567b811998-01-19 23:07:55 +000059 Arguments (only dir is required):
60
61 dir: the directory to byte-compile
62 maxlevels: maximum recursion level (default 10)
R. David Murray94f58c32010-12-17 16:29:07 +000063 ddir: the directory that will be prepended to the path to the
64 file as it is compiled into each byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +000065 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +030066 quiet: full output with False or 0, errors only with 1,
67 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +000068 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +000069 optimize: optimization level or -1 for level of the interpreter
Brett Cannonf1a8df02014-09-12 10:39:48 -040070 workers: maximum number of parallel workers
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080071 invalidation_mode: how the up-to-dateness of the pyc will be checked
Guido van Rossumc567b811998-01-19 23:07:55 +000072 """
Martin Panter88281ce2016-11-05 01:11:36 +000073 if workers is not None and workers < 0:
74 raise ValueError('workers must be greater or equal to 0')
75
Brett Cannonf1a8df02014-09-12 10:39:48 -040076 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
77 ddir=ddir)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080078 success = True
Berker Peksagd86ef052015-04-22 09:39:19 +030079 if workers is not None and workers != 1 and ProcessPoolExecutor is not None:
Brett Cannonf1a8df02014-09-12 10:39:48 -040080 workers = workers or None
81 with ProcessPoolExecutor(max_workers=workers) as executor:
82 results = executor.map(partial(compile_file,
83 ddir=ddir, force=force,
84 rx=rx, quiet=quiet,
85 legacy=legacy,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080086 optimize=optimize,
87 invalidation_mode=invalidation_mode),
Brett Cannonf1a8df02014-09-12 10:39:48 -040088 files)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080089 success = min(results, default=True)
Brett Cannonf1a8df02014-09-12 10:39:48 -040090 else:
91 for file in files:
92 if not compile_file(file, ddir, force, rx, quiet,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080093 legacy, optimize, invalidation_mode):
Brett Cannon1e3c3e92015-12-27 13:17:04 -080094 success = False
Fred Drake9065ea31999-03-29 20:25:40 +000095 return success
Guido van Rossumc567b811998-01-19 23:07:55 +000096
Berker Peksag6554b862014-10-15 11:10:57 +030097def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -080098 legacy=False, optimize=-1,
99 invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP):
Éric Araujo413d7b42010-12-23 18:44:31 +0000100 """Byte-compile one file.
101
102 Arguments (only fullname is required):
103
Barry Warsaw28a691b2010-04-17 00:19:56 +0000104 fullname: the file to byte-compile
R. David Murray94f58c32010-12-17 16:29:07 +0000105 ddir: if given, the directory name compiled in to the
106 byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000107 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +0300108 quiet: full output with False or 0, errors only with 1,
109 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +0000110 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +0000111 optimize: optimization level or -1 for level of the interpreter
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800112 invalidation_mode: how the up-to-dateness of the pyc will be checked
Matthias Klosec33b9022010-03-16 00:36:26 +0000113 """
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800114 success = True
Berker Peksag812a2b62016-10-01 00:54:18 +0300115 if quiet < 2 and isinstance(fullname, os.PathLike):
116 fullname = os.fspath(fullname)
Matthias Klosec33b9022010-03-16 00:36:26 +0000117 name = os.path.basename(fullname)
118 if ddir is not None:
119 dfile = os.path.join(ddir, name)
120 else:
121 dfile = None
122 if rx is not None:
123 mo = rx.search(fullname)
124 if mo:
125 return success
126 if os.path.isfile(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000127 if legacy:
Brett Cannonf299abd2015-04-13 14:21:02 -0400128 cfile = fullname + 'c'
Barry Warsaw28a691b2010-04-17 00:19:56 +0000129 else:
Georg Brandl8334fd92010-12-04 10:26:46 +0000130 if optimize >= 0:
Brett Cannonf299abd2015-04-13 14:21:02 -0400131 opt = optimize if optimize >= 1 else ''
Brett Cannon7822e122013-06-14 23:04:02 -0400132 cfile = importlib.util.cache_from_source(
Brett Cannonf299abd2015-04-13 14:21:02 -0400133 fullname, optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000134 else:
Brett Cannon7822e122013-06-14 23:04:02 -0400135 cfile = importlib.util.cache_from_source(fullname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136 cache_dir = os.path.dirname(cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +0000137 head, tail = name[:-3], name[-3:]
138 if tail == '.py':
139 if not force:
140 try:
141 mtime = int(os.stat(fullname).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800142 expect = struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
143 0, mtime)
Matthias Klosec33b9022010-03-16 00:36:26 +0000144 with open(cfile, 'rb') as chandle:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800145 actual = chandle.read(12)
Matthias Klosec33b9022010-03-16 00:36:26 +0000146 if expect == actual:
147 return success
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200148 except OSError:
Matthias Klosec33b9022010-03-16 00:36:26 +0000149 pass
150 if not quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200151 print('Compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000152 try:
Georg Brandl8334fd92010-12-04 10:26:46 +0000153 ok = py_compile.compile(fullname, cfile, dfile, True,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800154 optimize=optimize,
155 invalidation_mode=invalidation_mode)
Matthias Klosec33b9022010-03-16 00:36:26 +0000156 except py_compile.PyCompileError as err:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800157 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300158 if quiet >= 2:
159 return success
160 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200161 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000162 else:
163 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000164 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000165 msg = err.msg.encode(sys.stdout.encoding,
166 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000167 msg = msg.decode(sys.stdout.encoding)
168 print(msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200169 except (SyntaxError, UnicodeError, OSError) as e:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800170 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300171 if quiet >= 2:
172 return success
173 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200174 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000175 else:
176 print('*** ', end='')
177 print(e.__class__.__name__ + ':', e)
Matthias Klosec33b9022010-03-16 00:36:26 +0000178 else:
179 if ok == 0:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800180 success = False
Matthias Klosec33b9022010-03-16 00:36:26 +0000181 return success
182
Berker Peksag6554b862014-10-15 11:10:57 +0300183def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800184 legacy=False, optimize=-1,
185 invalidation_mode=py_compile.PycInvalidationMode.TIMESTAMP):
Guido van Rossumc567b811998-01-19 23:07:55 +0000186 """Byte-compile all module on sys.path.
187
188 Arguments (all optional):
189
Éric Araujo3b371cf2011-09-01 20:00:33 +0200190 skip_curdir: if true, skip current directory (default True)
Guido van Rossumc567b811998-01-19 23:07:55 +0000191 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000192 force: as for compile_dir() (default False)
Berker Peksag6554b862014-10-15 11:10:57 +0300193 quiet: as for compile_dir() (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000194 legacy: as for compile_dir() (default False)
Georg Brandl8334fd92010-12-04 10:26:46 +0000195 optimize: as for compile_dir() (default -1)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800196 invalidation_mode: as for compiler_dir()
Guido van Rossumc567b811998-01-19 23:07:55 +0000197 """
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800198 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000199 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 if (not dir or dir == os.curdir) and skip_curdir:
Berker Peksag6554b862014-10-15 11:10:57 +0300201 if quiet < 2:
202 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000203 else:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800204 success = success and compile_dir(
205 dir,
206 maxlevels,
207 None,
208 force,
209 quiet=quiet,
210 legacy=legacy,
211 optimize=optimize,
212 invalidation_mode=invalidation_mode,
213 )
Fred Drake9065ea31999-03-29 20:25:40 +0000214 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000215
Matthias Klosec33b9022010-03-16 00:36:26 +0000216
Guido van Rossum3bb54481994-08-29 10:52:58 +0000217def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000218 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000219 import argparse
220
221 parser = argparse.ArgumentParser(
222 description='Utilities to support installing Python libraries.')
R. David Murray94f58c32010-12-17 16:29:07 +0000223 parser.add_argument('-l', action='store_const', const=0,
224 default=10, dest='maxlevels',
225 help="don't recurse into subdirectories")
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500226 parser.add_argument('-r', type=int, dest='recursion',
227 help=('control the maximum recursion level. '
228 'if `-l` and `-r` options are specified, '
229 'then `-r` takes precedence.'))
R. David Murray650f1472010-11-20 21:18:51 +0000230 parser.add_argument('-f', action='store_true', dest='force',
231 help='force rebuild even if timestamps are up to date')
Berker Peksag6554b862014-10-15 11:10:57 +0300232 parser.add_argument('-q', action='count', dest='quiet', default=0,
233 help='output only error messages; -qq will suppress '
234 'the error messages as well.')
R. David Murray650f1472010-11-20 21:18:51 +0000235 parser.add_argument('-b', action='store_true', dest='legacy',
R. David Murray94f58c32010-12-17 16:29:07 +0000236 help='use legacy (pre-PEP3147) compiled file locations')
R. David Murray650f1472010-11-20 21:18:51 +0000237 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
R. David Murray94f58c32010-12-17 16:29:07 +0000238 help=('directory to prepend to file paths for use in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200239 'compile-time tracebacks and in runtime '
R. David Murray94f58c32010-12-17 16:29:07 +0000240 'tracebacks in cases where the source file is '
241 'unavailable'))
R. David Murray650f1472010-11-20 21:18:51 +0000242 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
Éric Araujo3b371cf2011-09-01 20:00:33 +0200243 help=('skip files matching the regular expression; '
244 'the regexp is searched for in the full path '
245 'of each file considered for compilation'))
R. David Murray650f1472010-11-20 21:18:51 +0000246 parser.add_argument('-i', metavar='FILE', dest='flist',
R. David Murray94f58c32010-12-17 16:29:07 +0000247 help=('add all the files and directories listed in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200248 'FILE to the list considered for compilation; '
249 'if "-", names are read from stdin'))
R. David Murray94f58c32010-12-17 16:29:07 +0000250 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
251 help=('zero or more file and directory names '
252 'to compile; if no arguments given, defaults '
253 'to the equivalent of -l sys.path'))
Brett Cannonf1a8df02014-09-12 10:39:48 -0400254 parser.add_argument('-j', '--workers', default=1,
255 type=int, help='Run compileall concurrently')
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800256 invalidation_modes = [mode.name.lower().replace('_', '-')
257 for mode in py_compile.PycInvalidationMode]
258 parser.add_argument('--invalidation-mode', default='timestamp',
259 choices=sorted(invalidation_modes),
260 help='How the pycs will be invalidated at runtime')
R. David Murray650f1472010-11-20 21:18:51 +0000261
Brett Cannonf1a8df02014-09-12 10:39:48 -0400262 args = parser.parse_args()
R. David Murray95333e32010-12-14 22:32:50 +0000263 compile_dests = args.compile_dest
264
R. David Murray650f1472010-11-20 21:18:51 +0000265 if args.rx:
266 import re
267 args.rx = re.compile(args.rx)
268
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500269
270 if args.recursion is not None:
271 maxlevels = args.recursion
272 else:
273 maxlevels = args.maxlevels
274
R. David Murray650f1472010-11-20 21:18:51 +0000275 # if flist is provided then load it
R. David Murray650f1472010-11-20 21:18:51 +0000276 if args.flist:
R. David Murray95333e32010-12-14 22:32:50 +0000277 try:
278 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
279 for line in f:
280 compile_dests.append(line.strip())
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200281 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +0300282 if args.quiet < 2:
283 print("Error reading file list {}".format(args.flist))
R. David Murray95333e32010-12-14 22:32:50 +0000284 return False
R. David Murray650f1472010-11-20 21:18:51 +0000285
Brett Cannonf1a8df02014-09-12 10:39:48 -0400286 if args.workers is not None:
287 args.workers = args.workers or None
288
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800289 ivl_mode = args.invalidation_mode.replace('-', '_').upper()
290 invalidation_mode = py_compile.PycInvalidationMode[ivl_mode]
291
R. David Murray95333e32010-12-14 22:32:50 +0000292 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000293 try:
R. David Murray650f1472010-11-20 21:18:51 +0000294 if compile_dests:
295 for dest in compile_dests:
R. David Murray5317e9c2010-12-16 19:08:51 +0000296 if os.path.isfile(dest):
297 if not compile_file(dest, args.ddir, args.force, args.rx,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800298 args.quiet, args.legacy,
299 invalidation_mode=invalidation_mode):
R. David Murray5317e9c2010-12-16 19:08:51 +0000300 success = False
301 else:
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500302 if not compile_dir(dest, maxlevels, args.ddir,
R. David Murray650f1472010-11-20 21:18:51 +0000303 args.force, args.rx, args.quiet,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800304 args.legacy, workers=args.workers,
305 invalidation_mode=invalidation_mode):
R. David Murray95333e32010-12-14 22:32:50 +0000306 success = False
R. David Murray95333e32010-12-14 22:32:50 +0000307 return success
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000308 else:
R David Murray8a1d1e62013-12-15 20:49:38 -0500309 return compile_path(legacy=args.legacy, force=args.force,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800310 quiet=args.quiet,
311 invalidation_mode=invalidation_mode)
Guido van Rossumc567b811998-01-19 23:07:55 +0000312 except KeyboardInterrupt:
Berker Peksag6554b862014-10-15 11:10:57 +0300313 if args.quiet < 2:
314 print("\n[interrupted]")
R. David Murray95333e32010-12-14 22:32:50 +0000315 return False
316 return True
R. David Murray650f1472010-11-20 21:18:51 +0000317
Guido van Rossum3bb54481994-08-29 10:52:58 +0000318
319if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000320 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000321 sys.exit(exit_status)