blob: bfac8efc804d06ee8b20081fd72722506c751844 [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):
Gregory P. Smithce720d32020-03-01 10:42:56 -080044 yield fullname, ddir
Brett Cannonf1a8df02014-09-12 10:39:48 -040045 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
Gregory P. Smithce720d32020-03-01 10:42:56 -080079 files_and_ddirs = _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:
Gregory P. Smithce720d32020-03-01 10:42:56 -080086 results = executor.map(
87 partial(_compile_file_tuple,
88 force=force, rx=rx, quiet=quiet,
89 legacy=legacy, optimize=optimize,
90 invalidation_mode=invalidation_mode,
91 ),
92 files_and_ddirs)
Brett Cannon1e3c3e92015-12-27 13:17:04 -080093 success = min(results, default=True)
Brett Cannonf1a8df02014-09-12 10:39:48 -040094 else:
Gregory P. Smithce720d32020-03-01 10:42:56 -080095 for file, dfile in files_and_ddirs:
96 if not compile_file(file, dfile, 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
Gregory P. Smithce720d32020-03-01 10:42:56 -0800101def _compile_file_tuple(file_and_dfile, **kwargs):
102 """Needs to be toplevel for ProcessPoolExecutor."""
103 file, dfile = file_and_dfile
104 return compile_file(file, dfile, **kwargs)
105
Berker Peksag6554b862014-10-15 11:10:57 +0300106def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800107 legacy=False, optimize=-1,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400108 invalidation_mode=None):
Éric Araujo413d7b42010-12-23 18:44:31 +0000109 """Byte-compile one file.
110
111 Arguments (only fullname is required):
112
Barry Warsaw28a691b2010-04-17 00:19:56 +0000113 fullname: the file to byte-compile
R. David Murray94f58c32010-12-17 16:29:07 +0000114 ddir: if given, the directory name compiled in to the
115 byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +0300117 quiet: full output with False or 0, errors only with 1,
118 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +0000119 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +0000120 optimize: optimization level or -1 for level of the interpreter
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800121 invalidation_mode: how the up-to-dateness of the pyc will be checked
Matthias Klosec33b9022010-03-16 00:36:26 +0000122 """
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800123 success = True
Berker Peksag812a2b62016-10-01 00:54:18 +0300124 if quiet < 2 and isinstance(fullname, os.PathLike):
125 fullname = os.fspath(fullname)
Matthias Klosec33b9022010-03-16 00:36:26 +0000126 name = os.path.basename(fullname)
127 if ddir is not None:
128 dfile = os.path.join(ddir, name)
129 else:
130 dfile = None
131 if rx is not None:
132 mo = rx.search(fullname)
133 if mo:
134 return success
135 if os.path.isfile(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136 if legacy:
Brett Cannonf299abd2015-04-13 14:21:02 -0400137 cfile = fullname + 'c'
Barry Warsaw28a691b2010-04-17 00:19:56 +0000138 else:
Georg Brandl8334fd92010-12-04 10:26:46 +0000139 if optimize >= 0:
Brett Cannonf299abd2015-04-13 14:21:02 -0400140 opt = optimize if optimize >= 1 else ''
Brett Cannon7822e122013-06-14 23:04:02 -0400141 cfile = importlib.util.cache_from_source(
Brett Cannonf299abd2015-04-13 14:21:02 -0400142 fullname, optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000143 else:
Brett Cannon7822e122013-06-14 23:04:02 -0400144 cfile = importlib.util.cache_from_source(fullname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000145 cache_dir = os.path.dirname(cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +0000146 head, tail = name[:-3], name[-3:]
147 if tail == '.py':
148 if not force:
149 try:
150 mtime = int(os.stat(fullname).st_mtime)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800151 expect = struct.pack('<4sll', importlib.util.MAGIC_NUMBER,
152 0, mtime)
Matthias Klosec33b9022010-03-16 00:36:26 +0000153 with open(cfile, 'rb') as chandle:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800154 actual = chandle.read(12)
Matthias Klosec33b9022010-03-16 00:36:26 +0000155 if expect == actual:
156 return success
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200157 except OSError:
Matthias Klosec33b9022010-03-16 00:36:26 +0000158 pass
159 if not quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200160 print('Compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000161 try:
Georg Brandl8334fd92010-12-04 10:26:46 +0000162 ok = py_compile.compile(fullname, cfile, dfile, True,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800163 optimize=optimize,
164 invalidation_mode=invalidation_mode)
Matthias Klosec33b9022010-03-16 00:36:26 +0000165 except py_compile.PyCompileError as err:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800166 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300167 if quiet >= 2:
168 return success
169 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200170 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000171 else:
172 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000173 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000174 msg = err.msg.encode(sys.stdout.encoding,
175 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000176 msg = msg.decode(sys.stdout.encoding)
177 print(msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200178 except (SyntaxError, UnicodeError, OSError) as e:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800179 success = False
Berker Peksag6554b862014-10-15 11:10:57 +0300180 if quiet >= 2:
181 return success
182 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200183 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000184 else:
185 print('*** ', end='')
186 print(e.__class__.__name__ + ':', e)
Matthias Klosec33b9022010-03-16 00:36:26 +0000187 else:
188 if ok == 0:
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800189 success = False
Matthias Klosec33b9022010-03-16 00:36:26 +0000190 return success
191
Berker Peksag6554b862014-10-15 11:10:57 +0300192def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800193 legacy=False, optimize=-1,
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400194 invalidation_mode=None):
Guido van Rossumc567b811998-01-19 23:07:55 +0000195 """Byte-compile all module on sys.path.
196
197 Arguments (all optional):
198
Éric Araujo3b371cf2011-09-01 20:00:33 +0200199 skip_curdir: if true, skip current directory (default True)
Guido van Rossumc567b811998-01-19 23:07:55 +0000200 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000201 force: as for compile_dir() (default False)
Berker Peksag6554b862014-10-15 11:10:57 +0300202 quiet: as for compile_dir() (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000203 legacy: as for compile_dir() (default False)
Georg Brandl8334fd92010-12-04 10:26:46 +0000204 optimize: as for compile_dir() (default -1)
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800205 invalidation_mode: as for compiler_dir()
Guido van Rossumc567b811998-01-19 23:07:55 +0000206 """
Brett Cannon1e3c3e92015-12-27 13:17:04 -0800207 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000208 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000209 if (not dir or dir == os.curdir) and skip_curdir:
Berker Peksag6554b862014-10-15 11:10:57 +0300210 if quiet < 2:
211 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000212 else:
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800213 success = success and compile_dir(
214 dir,
215 maxlevels,
216 None,
217 force,
218 quiet=quiet,
219 legacy=legacy,
220 optimize=optimize,
221 invalidation_mode=invalidation_mode,
222 )
Fred Drake9065ea31999-03-29 20:25:40 +0000223 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000224
Matthias Klosec33b9022010-03-16 00:36:26 +0000225
Guido van Rossum3bb54481994-08-29 10:52:58 +0000226def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000227 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000228 import argparse
229
230 parser = argparse.ArgumentParser(
231 description='Utilities to support installing Python libraries.')
R. David Murray94f58c32010-12-17 16:29:07 +0000232 parser.add_argument('-l', action='store_const', const=0,
233 default=10, dest='maxlevels',
234 help="don't recurse into subdirectories")
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500235 parser.add_argument('-r', type=int, dest='recursion',
236 help=('control the maximum recursion level. '
237 'if `-l` and `-r` options are specified, '
238 'then `-r` takes precedence.'))
R. David Murray650f1472010-11-20 21:18:51 +0000239 parser.add_argument('-f', action='store_true', dest='force',
240 help='force rebuild even if timestamps are up to date')
Berker Peksag6554b862014-10-15 11:10:57 +0300241 parser.add_argument('-q', action='count', dest='quiet', default=0,
242 help='output only error messages; -qq will suppress '
243 'the error messages as well.')
R. David Murray650f1472010-11-20 21:18:51 +0000244 parser.add_argument('-b', action='store_true', dest='legacy',
R. David Murray94f58c32010-12-17 16:29:07 +0000245 help='use legacy (pre-PEP3147) compiled file locations')
R. David Murray650f1472010-11-20 21:18:51 +0000246 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
R. David Murray94f58c32010-12-17 16:29:07 +0000247 help=('directory to prepend to file paths for use in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200248 'compile-time tracebacks and in runtime '
R. David Murray94f58c32010-12-17 16:29:07 +0000249 'tracebacks in cases where the source file is '
250 'unavailable'))
R. David Murray650f1472010-11-20 21:18:51 +0000251 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
Éric Araujo3b371cf2011-09-01 20:00:33 +0200252 help=('skip files matching the regular expression; '
253 'the regexp is searched for in the full path '
254 'of each file considered for compilation'))
R. David Murray650f1472010-11-20 21:18:51 +0000255 parser.add_argument('-i', metavar='FILE', dest='flist',
R. David Murray94f58c32010-12-17 16:29:07 +0000256 help=('add all the files and directories listed in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200257 'FILE to the list considered for compilation; '
258 'if "-", names are read from stdin'))
R. David Murray94f58c32010-12-17 16:29:07 +0000259 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
260 help=('zero or more file and directory names '
261 'to compile; if no arguments given, defaults '
262 'to the equivalent of -l sys.path'))
Brett Cannonf1a8df02014-09-12 10:39:48 -0400263 parser.add_argument('-j', '--workers', default=1,
264 type=int, help='Run compileall concurrently')
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800265 invalidation_modes = [mode.name.lower().replace('_', '-')
266 for mode in py_compile.PycInvalidationMode]
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400267 parser.add_argument('--invalidation-mode',
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800268 choices=sorted(invalidation_modes),
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400269 help=('set .pyc invalidation mode; defaults to '
270 '"checked-hash" if the SOURCE_DATE_EPOCH '
271 'environment variable is set, and '
272 '"timestamp" otherwise.'))
R. David Murray650f1472010-11-20 21:18:51 +0000273
Brett Cannonf1a8df02014-09-12 10:39:48 -0400274 args = parser.parse_args()
R. David Murray95333e32010-12-14 22:32:50 +0000275 compile_dests = args.compile_dest
276
R. David Murray650f1472010-11-20 21:18:51 +0000277 if args.rx:
278 import re
279 args.rx = re.compile(args.rx)
280
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500281
282 if args.recursion is not None:
283 maxlevels = args.recursion
284 else:
285 maxlevels = args.maxlevels
286
R. David Murray650f1472010-11-20 21:18:51 +0000287 # if flist is provided then load it
R. David Murray650f1472010-11-20 21:18:51 +0000288 if args.flist:
R. David Murray95333e32010-12-14 22:32:50 +0000289 try:
290 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
291 for line in f:
292 compile_dests.append(line.strip())
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200293 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +0300294 if args.quiet < 2:
295 print("Error reading file list {}".format(args.flist))
R. David Murray95333e32010-12-14 22:32:50 +0000296 return False
R. David Murray650f1472010-11-20 21:18:51 +0000297
Elvis Pranskevichusa6b3ec52018-10-10 12:43:14 -0400298 if args.invalidation_mode:
299 ivl_mode = args.invalidation_mode.replace('-', '_').upper()
300 invalidation_mode = py_compile.PycInvalidationMode[ivl_mode]
301 else:
302 invalidation_mode = None
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800303
R. David Murray95333e32010-12-14 22:32:50 +0000304 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000305 try:
R. David Murray650f1472010-11-20 21:18:51 +0000306 if compile_dests:
307 for dest in compile_dests:
R. David Murray5317e9c2010-12-16 19:08:51 +0000308 if os.path.isfile(dest):
309 if not compile_file(dest, args.ddir, args.force, args.rx,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800310 args.quiet, args.legacy,
311 invalidation_mode=invalidation_mode):
R. David Murray5317e9c2010-12-16 19:08:51 +0000312 success = False
313 else:
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500314 if not compile_dir(dest, maxlevels, args.ddir,
R. David Murray650f1472010-11-20 21:18:51 +0000315 args.force, args.rx, args.quiet,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800316 args.legacy, workers=args.workers,
317 invalidation_mode=invalidation_mode):
R. David Murray95333e32010-12-14 22:32:50 +0000318 success = False
R. David Murray95333e32010-12-14 22:32:50 +0000319 return success
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000320 else:
R David Murray8a1d1e62013-12-15 20:49:38 -0500321 return compile_path(legacy=args.legacy, force=args.force,
Benjamin Peterson42aa93b2017-12-09 10:26:52 -0800322 quiet=args.quiet,
323 invalidation_mode=invalidation_mode)
Guido van Rossumc567b811998-01-19 23:07:55 +0000324 except KeyboardInterrupt:
Berker Peksag6554b862014-10-15 11:10:57 +0300325 if args.quiet < 2:
326 print("\n[interrupted]")
R. David Murray95333e32010-12-14 22:32:50 +0000327 return False
328 return True
R. David Murray650f1472010-11-20 21:18:51 +0000329
Guido van Rossum3bb54481994-08-29 10:52:58 +0000330
331if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000332 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000333 sys.exit(exit_status)