blob: aeaaf8e9ce1f9a2c60261ebf1d0cc90f55ac7e56 [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):
Brett Cannonf1a8df02014-09-12 10:39:48 -040028 if not quiet:
29 print('Listing {!r}...'.format(dir))
30 try:
31 names = os.listdir(dir)
32 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +030033 if quiet < 2:
34 print("Can't list {!r}".format(dir))
Brett Cannonf1a8df02014-09-12 10:39:48 -040035 names = []
36 names.sort()
37 for name in names:
38 if name == '__pycache__':
39 continue
40 fullname = os.path.join(dir, name)
41 if ddir is not None:
42 dfile = os.path.join(ddir, name)
43 else:
44 dfile = None
45 if not os.path.isdir(fullname):
46 yield fullname
47 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
48 os.path.isdir(fullname) and not os.path.islink(fullname)):
49 yield from _walk_dir(fullname, ddir=dfile,
50 maxlevels=maxlevels - 1, quiet=quiet)
51
Georg Brandl8334fd92010-12-04 10:26:46 +000052def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
Berker Peksag6554b862014-10-15 11:10:57 +030053 quiet=0, legacy=False, optimize=-1, workers=1):
Guido van Rossumc567b811998-01-19 23:07:55 +000054 """Byte-compile all modules in the given directory tree.
Guido van Rossum3bb54481994-08-29 10:52:58 +000055
Guido van Rossumc567b811998-01-19 23:07:55 +000056 Arguments (only dir is required):
57
58 dir: the directory to byte-compile
59 maxlevels: maximum recursion level (default 10)
R. David Murray94f58c32010-12-17 16:29:07 +000060 ddir: the directory that will be prepended to the path to the
61 file as it is compiled into each byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +000062 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +030063 quiet: full output with False or 0, errors only with 1,
64 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +000065 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +000066 optimize: optimization level or -1 for level of the interpreter
Brett Cannonf1a8df02014-09-12 10:39:48 -040067 workers: maximum number of parallel workers
Guido van Rossumc567b811998-01-19 23:07:55 +000068 """
Brett Cannonf1a8df02014-09-12 10:39:48 -040069 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
70 ddir=ddir)
Fred Drake9065ea31999-03-29 20:25:40 +000071 success = 1
Brett Cannonf1a8df02014-09-12 10:39:48 -040072 if workers is not None and workers != 1:
73 if workers < 0:
74 raise ValueError('workers must be greater or equal to 0')
75 if ProcessPoolExecutor is None:
76 raise NotImplementedError('multiprocessing support not available')
77
78 workers = workers or None
79 with ProcessPoolExecutor(max_workers=workers) as executor:
80 results = executor.map(partial(compile_file,
81 ddir=ddir, force=force,
82 rx=rx, quiet=quiet,
83 legacy=legacy,
84 optimize=optimize),
85 files)
86 success = min(results, default=1)
87 else:
88 for file in files:
89 if not compile_file(file, ddir, force, rx, quiet,
Georg Brandl8334fd92010-12-04 10:26:46 +000090 legacy, optimize):
Matthias Klosec33b9022010-03-16 00:36:26 +000091 success = 0
Fred Drake9065ea31999-03-29 20:25:40 +000092 return success
Guido van Rossumc567b811998-01-19 23:07:55 +000093
Berker Peksag6554b862014-10-15 11:10:57 +030094def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0,
Georg Brandl8334fd92010-12-04 10:26:46 +000095 legacy=False, optimize=-1):
Éric Araujo413d7b42010-12-23 18:44:31 +000096 """Byte-compile one file.
97
98 Arguments (only fullname is required):
99
Barry Warsaw28a691b2010-04-17 00:19:56 +0000100 fullname: the file to byte-compile
R. David Murray94f58c32010-12-17 16:29:07 +0000101 ddir: if given, the directory name compiled in to the
102 byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000103 force: if True, force compilation, even if timestamps are up-to-date
Berker Peksag6554b862014-10-15 11:10:57 +0300104 quiet: full output with False or 0, errors only with 1,
105 no output with 2
Barry Warsaw28a691b2010-04-17 00:19:56 +0000106 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +0000107 optimize: optimization level or -1 for level of the interpreter
Matthias Klosec33b9022010-03-16 00:36:26 +0000108 """
109 success = 1
110 name = os.path.basename(fullname)
111 if ddir is not None:
112 dfile = os.path.join(ddir, name)
113 else:
114 dfile = None
115 if rx is not None:
116 mo = rx.search(fullname)
117 if mo:
118 return success
119 if os.path.isfile(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000120 if legacy:
Brett Cannonf299abd2015-04-13 14:21:02 -0400121 cfile = fullname + 'c'
Barry Warsaw28a691b2010-04-17 00:19:56 +0000122 else:
Georg Brandl8334fd92010-12-04 10:26:46 +0000123 if optimize >= 0:
Brett Cannonf299abd2015-04-13 14:21:02 -0400124 opt = optimize if optimize >= 1 else ''
Brett Cannon7822e122013-06-14 23:04:02 -0400125 cfile = importlib.util.cache_from_source(
Brett Cannonf299abd2015-04-13 14:21:02 -0400126 fullname, optimization=opt)
Georg Brandl8334fd92010-12-04 10:26:46 +0000127 else:
Brett Cannon7822e122013-06-14 23:04:02 -0400128 cfile = importlib.util.cache_from_source(fullname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000129 cache_dir = os.path.dirname(cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +0000130 head, tail = name[:-3], name[-3:]
131 if tail == '.py':
132 if not force:
133 try:
134 mtime = int(os.stat(fullname).st_mtime)
Brett Cannon7822e122013-06-14 23:04:02 -0400135 expect = struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
136 mtime)
Matthias Klosec33b9022010-03-16 00:36:26 +0000137 with open(cfile, 'rb') as chandle:
138 actual = chandle.read(8)
139 if expect == actual:
140 return success
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200141 except OSError:
Matthias Klosec33b9022010-03-16 00:36:26 +0000142 pass
143 if not quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200144 print('Compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000145 try:
Georg Brandl8334fd92010-12-04 10:26:46 +0000146 ok = py_compile.compile(fullname, cfile, dfile, True,
147 optimize=optimize)
Matthias Klosec33b9022010-03-16 00:36:26 +0000148 except py_compile.PyCompileError as err:
Berker Peksag6554b862014-10-15 11:10:57 +0300149 success = 0
150 if quiet >= 2:
151 return success
152 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200153 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000154 else:
155 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000156 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000157 msg = err.msg.encode(sys.stdout.encoding,
158 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000159 msg = msg.decode(sys.stdout.encoding)
160 print(msg)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200161 except (SyntaxError, UnicodeError, OSError) as e:
Berker Peksag6554b862014-10-15 11:10:57 +0300162 success = 0
163 if quiet >= 2:
164 return success
165 elif quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200166 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000167 else:
168 print('*** ', end='')
169 print(e.__class__.__name__ + ':', e)
Matthias Klosec33b9022010-03-16 00:36:26 +0000170 else:
171 if ok == 0:
172 success = 0
173 return success
174
Berker Peksag6554b862014-10-15 11:10:57 +0300175def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=0,
Georg Brandl8334fd92010-12-04 10:26:46 +0000176 legacy=False, optimize=-1):
Guido van Rossumc567b811998-01-19 23:07:55 +0000177 """Byte-compile all module on sys.path.
178
179 Arguments (all optional):
180
Éric Araujo3b371cf2011-09-01 20:00:33 +0200181 skip_curdir: if true, skip current directory (default True)
Guido van Rossumc567b811998-01-19 23:07:55 +0000182 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000183 force: as for compile_dir() (default False)
Berker Peksag6554b862014-10-15 11:10:57 +0300184 quiet: as for compile_dir() (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000185 legacy: as for compile_dir() (default False)
Georg Brandl8334fd92010-12-04 10:26:46 +0000186 optimize: as for compile_dir() (default -1)
Guido van Rossumc567b811998-01-19 23:07:55 +0000187 """
Fred Drake9065ea31999-03-29 20:25:40 +0000188 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +0000189 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 if (not dir or dir == os.curdir) and skip_curdir:
Berker Peksag6554b862014-10-15 11:10:57 +0300191 if quiet < 2:
192 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000193 else:
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000194 success = success and compile_dir(dir, maxlevels, None,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000195 force, quiet=quiet,
Georg Brandl8334fd92010-12-04 10:26:46 +0000196 legacy=legacy, optimize=optimize)
Fred Drake9065ea31999-03-29 20:25:40 +0000197 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000198
Matthias Klosec33b9022010-03-16 00:36:26 +0000199
Guido van Rossum3bb54481994-08-29 10:52:58 +0000200def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000201 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000202 import argparse
203
204 parser = argparse.ArgumentParser(
205 description='Utilities to support installing Python libraries.')
R. David Murray94f58c32010-12-17 16:29:07 +0000206 parser.add_argument('-l', action='store_const', const=0,
207 default=10, dest='maxlevels',
208 help="don't recurse into subdirectories")
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500209 parser.add_argument('-r', type=int, dest='recursion',
210 help=('control the maximum recursion level. '
211 'if `-l` and `-r` options are specified, '
212 'then `-r` takes precedence.'))
R. David Murray650f1472010-11-20 21:18:51 +0000213 parser.add_argument('-f', action='store_true', dest='force',
214 help='force rebuild even if timestamps are up to date')
Berker Peksag6554b862014-10-15 11:10:57 +0300215 parser.add_argument('-q', action='count', dest='quiet', default=0,
216 help='output only error messages; -qq will suppress '
217 'the error messages as well.')
R. David Murray650f1472010-11-20 21:18:51 +0000218 parser.add_argument('-b', action='store_true', dest='legacy',
R. David Murray94f58c32010-12-17 16:29:07 +0000219 help='use legacy (pre-PEP3147) compiled file locations')
R. David Murray650f1472010-11-20 21:18:51 +0000220 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
R. David Murray94f58c32010-12-17 16:29:07 +0000221 help=('directory to prepend to file paths for use in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200222 'compile-time tracebacks and in runtime '
R. David Murray94f58c32010-12-17 16:29:07 +0000223 'tracebacks in cases where the source file is '
224 'unavailable'))
R. David Murray650f1472010-11-20 21:18:51 +0000225 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
Éric Araujo3b371cf2011-09-01 20:00:33 +0200226 help=('skip files matching the regular expression; '
227 'the regexp is searched for in the full path '
228 'of each file considered for compilation'))
R. David Murray650f1472010-11-20 21:18:51 +0000229 parser.add_argument('-i', metavar='FILE', dest='flist',
R. David Murray94f58c32010-12-17 16:29:07 +0000230 help=('add all the files and directories listed in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200231 'FILE to the list considered for compilation; '
232 'if "-", names are read from stdin'))
R. David Murray94f58c32010-12-17 16:29:07 +0000233 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
234 help=('zero or more file and directory names '
235 'to compile; if no arguments given, defaults '
236 'to the equivalent of -l sys.path'))
Brett Cannonf1a8df02014-09-12 10:39:48 -0400237 parser.add_argument('-j', '--workers', default=1,
238 type=int, help='Run compileall concurrently')
R. David Murray650f1472010-11-20 21:18:51 +0000239
Brett Cannonf1a8df02014-09-12 10:39:48 -0400240 args = parser.parse_args()
R. David Murray95333e32010-12-14 22:32:50 +0000241 compile_dests = args.compile_dest
242
243 if (args.ddir and (len(compile_dests) != 1
244 or not os.path.isdir(compile_dests[0]))):
245 parser.exit('-d destdir requires exactly one directory argument')
R. David Murray650f1472010-11-20 21:18:51 +0000246 if args.rx:
247 import re
248 args.rx = re.compile(args.rx)
249
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500250
251 if args.recursion is not None:
252 maxlevels = args.recursion
253 else:
254 maxlevels = args.maxlevels
255
R. David Murray650f1472010-11-20 21:18:51 +0000256 # if flist is provided then load it
R. David Murray650f1472010-11-20 21:18:51 +0000257 if args.flist:
R. David Murray95333e32010-12-14 22:32:50 +0000258 try:
259 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
260 for line in f:
261 compile_dests.append(line.strip())
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200262 except OSError:
Berker Peksag6554b862014-10-15 11:10:57 +0300263 if args.quiet < 2:
264 print("Error reading file list {}".format(args.flist))
R. David Murray95333e32010-12-14 22:32:50 +0000265 return False
R. David Murray650f1472010-11-20 21:18:51 +0000266
Brett Cannonf1a8df02014-09-12 10:39:48 -0400267 if args.workers is not None:
268 args.workers = args.workers or None
269
R. David Murray95333e32010-12-14 22:32:50 +0000270 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000271 try:
R. David Murray650f1472010-11-20 21:18:51 +0000272 if compile_dests:
273 for dest in compile_dests:
R. David Murray5317e9c2010-12-16 19:08:51 +0000274 if os.path.isfile(dest):
275 if not compile_file(dest, args.ddir, args.force, args.rx,
276 args.quiet, args.legacy):
277 success = False
278 else:
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500279 if not compile_dir(dest, maxlevels, args.ddir,
R. David Murray650f1472010-11-20 21:18:51 +0000280 args.force, args.rx, args.quiet,
Brett Cannonf1a8df02014-09-12 10:39:48 -0400281 args.legacy, workers=args.workers):
R. David Murray95333e32010-12-14 22:32:50 +0000282 success = False
R. David Murray95333e32010-12-14 22:32:50 +0000283 return success
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000284 else:
R David Murray8a1d1e62013-12-15 20:49:38 -0500285 return compile_path(legacy=args.legacy, force=args.force,
286 quiet=args.quiet)
Guido van Rossumc567b811998-01-19 23:07:55 +0000287 except KeyboardInterrupt:
Berker Peksag6554b862014-10-15 11:10:57 +0300288 if args.quiet < 2:
289 print("\n[interrupted]")
R. David Murray95333e32010-12-14 22:32:50 +0000290 return False
291 return True
R. David Murray650f1472010-11-20 21:18:51 +0000292
Guido van Rossum3bb54481994-08-29 10:52:58 +0000293
294if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000295 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000296 sys.exit(exit_status)