blob: f1c9d27ad6ff6a774a3b478a12be6b22c8404e8b [file] [log] [blame]
Éric Araujo2e579f02010-11-20 21:53:02 +00001"""Module/script to byte-compile all .py files to .pyc (or .pyo) 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
Brett Cannonf1a8df02014-09-12 10:39:48 -040027def _walk_dir(dir, ddir=None, maxlevels=10, quiet=False):
28 if not quiet:
29 print('Listing {!r}...'.format(dir))
30 try:
31 names = os.listdir(dir)
32 except OSError:
33 print("Can't list {!r}".format(dir))
34 names = []
35 names.sort()
36 for name in names:
37 if name == '__pycache__':
38 continue
39 fullname = os.path.join(dir, name)
40 if ddir is not None:
41 dfile = os.path.join(ddir, name)
42 else:
43 dfile = None
44 if not os.path.isdir(fullname):
45 yield fullname
46 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
47 os.path.isdir(fullname) and not os.path.islink(fullname)):
48 yield from _walk_dir(fullname, ddir=dfile,
49 maxlevels=maxlevels - 1, quiet=quiet)
50
Georg Brandl8334fd92010-12-04 10:26:46 +000051def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
Brett Cannonf1a8df02014-09-12 10:39:48 -040052 quiet=False, legacy=False, optimize=-1, workers=1):
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
62 quiet: if True, be quiet during compilation
63 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +000064 optimize: optimization level or -1 for level of the interpreter
Brett Cannonf1a8df02014-09-12 10:39:48 -040065 workers: maximum number of parallel workers
Guido van Rossumc567b811998-01-19 23:07:55 +000066 """
Brett Cannonf1a8df02014-09-12 10:39:48 -040067 files = _walk_dir(dir, quiet=quiet, maxlevels=maxlevels,
68 ddir=ddir)
Fred Drake9065ea31999-03-29 20:25:40 +000069 success = 1
Brett Cannonf1a8df02014-09-12 10:39:48 -040070 if workers is not None and workers != 1:
71 if workers < 0:
72 raise ValueError('workers must be greater or equal to 0')
73 if ProcessPoolExecutor is None:
74 raise NotImplementedError('multiprocessing support not available')
75
76 workers = workers or None
77 with ProcessPoolExecutor(max_workers=workers) as executor:
78 results = executor.map(partial(compile_file,
79 ddir=ddir, force=force,
80 rx=rx, quiet=quiet,
81 legacy=legacy,
82 optimize=optimize),
83 files)
84 success = min(results, default=1)
85 else:
86 for file in files:
87 if not compile_file(file, ddir, force, rx, quiet,
Georg Brandl8334fd92010-12-04 10:26:46 +000088 legacy, optimize):
Matthias Klosec33b9022010-03-16 00:36:26 +000089 success = 0
Fred Drake9065ea31999-03-29 20:25:40 +000090 return success
Guido van Rossumc567b811998-01-19 23:07:55 +000091
Éric Araujo413d7b42010-12-23 18:44:31 +000092def compile_file(fullname, ddir=None, force=False, rx=None, quiet=False,
Georg Brandl8334fd92010-12-04 10:26:46 +000093 legacy=False, optimize=-1):
Éric Araujo413d7b42010-12-23 18:44:31 +000094 """Byte-compile one file.
95
96 Arguments (only fullname is required):
97
Barry Warsaw28a691b2010-04-17 00:19:56 +000098 fullname: the file to byte-compile
R. David Murray94f58c32010-12-17 16:29:07 +000099 ddir: if given, the directory name compiled in to the
100 byte-code file.
Barry Warsaw28a691b2010-04-17 00:19:56 +0000101 force: if True, force compilation, even if timestamps are up-to-date
102 quiet: if True, be quiet during compilation
103 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Georg Brandl8334fd92010-12-04 10:26:46 +0000104 optimize: optimization level or -1 for level of the interpreter
Matthias Klosec33b9022010-03-16 00:36:26 +0000105 """
106 success = 1
107 name = os.path.basename(fullname)
108 if ddir is not None:
109 dfile = os.path.join(ddir, name)
110 else:
111 dfile = None
112 if rx is not None:
113 mo = rx.search(fullname)
114 if mo:
115 return success
116 if os.path.isfile(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +0000117 if legacy:
118 cfile = fullname + ('c' if __debug__ else 'o')
119 else:
Georg Brandl8334fd92010-12-04 10:26:46 +0000120 if optimize >= 0:
Brett Cannon7822e122013-06-14 23:04:02 -0400121 cfile = importlib.util.cache_from_source(
122 fullname, debug_override=not optimize)
Georg Brandl8334fd92010-12-04 10:26:46 +0000123 else:
Brett Cannon7822e122013-06-14 23:04:02 -0400124 cfile = importlib.util.cache_from_source(fullname)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000125 cache_dir = os.path.dirname(cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +0000126 head, tail = name[:-3], name[-3:]
127 if tail == '.py':
128 if not force:
129 try:
130 mtime = int(os.stat(fullname).st_mtime)
Brett Cannon7822e122013-06-14 23:04:02 -0400131 expect = struct.pack('<4sl', importlib.util.MAGIC_NUMBER,
132 mtime)
Matthias Klosec33b9022010-03-16 00:36:26 +0000133 with open(cfile, 'rb') as chandle:
134 actual = chandle.read(8)
135 if expect == actual:
136 return success
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200137 except OSError:
Matthias Klosec33b9022010-03-16 00:36:26 +0000138 pass
139 if not quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200140 print('Compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000141 try:
Georg Brandl8334fd92010-12-04 10:26:46 +0000142 ok = py_compile.compile(fullname, cfile, dfile, True,
143 optimize=optimize)
Matthias Klosec33b9022010-03-16 00:36:26 +0000144 except py_compile.PyCompileError as err:
145 if quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200146 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000147 else:
148 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000149 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000150 msg = err.msg.encode(sys.stdout.encoding,
151 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000152 msg = msg.decode(sys.stdout.encoding)
153 print(msg)
Matthias Klosec33b9022010-03-16 00:36:26 +0000154 success = 0
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200155 except (SyntaxError, UnicodeError, OSError) as e:
Matthias Klosec33b9022010-03-16 00:36:26 +0000156 if quiet:
Victor Stinner53071262011-05-11 00:36:28 +0200157 print('*** Error compiling {!r}...'.format(fullname))
Matthias Klosec33b9022010-03-16 00:36:26 +0000158 else:
159 print('*** ', end='')
160 print(e.__class__.__name__ + ':', e)
161 success = 0
162 else:
163 if ok == 0:
164 success = 0
165 return success
166
Barry Warsaw28a691b2010-04-17 00:19:56 +0000167def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=False,
Georg Brandl8334fd92010-12-04 10:26:46 +0000168 legacy=False, optimize=-1):
Guido van Rossumc567b811998-01-19 23:07:55 +0000169 """Byte-compile all module on sys.path.
170
171 Arguments (all optional):
172
Éric Araujo3b371cf2011-09-01 20:00:33 +0200173 skip_curdir: if true, skip current directory (default True)
Guido van Rossumc567b811998-01-19 23:07:55 +0000174 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000175 force: as for compile_dir() (default False)
176 quiet: as for compile_dir() (default False)
177 legacy: as for compile_dir() (default False)
Georg Brandl8334fd92010-12-04 10:26:46 +0000178 optimize: as for compile_dir() (default -1)
Guido van Rossumc567b811998-01-19 23:07:55 +0000179 """
Fred Drake9065ea31999-03-29 20:25:40 +0000180 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +0000181 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 if (not dir or dir == os.curdir) and skip_curdir:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000183 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 else:
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000185 success = success and compile_dir(dir, maxlevels, None,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000186 force, quiet=quiet,
Georg Brandl8334fd92010-12-04 10:26:46 +0000187 legacy=legacy, optimize=optimize)
Fred Drake9065ea31999-03-29 20:25:40 +0000188 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000189
Matthias Klosec33b9022010-03-16 00:36:26 +0000190
Guido van Rossum3bb54481994-08-29 10:52:58 +0000191def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000192 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000193 import argparse
194
195 parser = argparse.ArgumentParser(
196 description='Utilities to support installing Python libraries.')
R. David Murray94f58c32010-12-17 16:29:07 +0000197 parser.add_argument('-l', action='store_const', const=0,
198 default=10, dest='maxlevels',
199 help="don't recurse into subdirectories")
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500200 parser.add_argument('-r', type=int, dest='recursion',
201 help=('control the maximum recursion level. '
202 'if `-l` and `-r` options are specified, '
203 'then `-r` takes precedence.'))
R. David Murray650f1472010-11-20 21:18:51 +0000204 parser.add_argument('-f', action='store_true', dest='force',
205 help='force rebuild even if timestamps are up to date')
206 parser.add_argument('-q', action='store_true', dest='quiet',
R. David Murray94f58c32010-12-17 16:29:07 +0000207 help='output only error messages')
R. David Murray650f1472010-11-20 21:18:51 +0000208 parser.add_argument('-b', action='store_true', dest='legacy',
R. David Murray94f58c32010-12-17 16:29:07 +0000209 help='use legacy (pre-PEP3147) compiled file locations')
R. David Murray650f1472010-11-20 21:18:51 +0000210 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
R. David Murray94f58c32010-12-17 16:29:07 +0000211 help=('directory to prepend to file paths for use in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200212 'compile-time tracebacks and in runtime '
R. David Murray94f58c32010-12-17 16:29:07 +0000213 'tracebacks in cases where the source file is '
214 'unavailable'))
R. David Murray650f1472010-11-20 21:18:51 +0000215 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
Éric Araujo3b371cf2011-09-01 20:00:33 +0200216 help=('skip files matching the regular expression; '
217 'the regexp is searched for in the full path '
218 'of each file considered for compilation'))
R. David Murray650f1472010-11-20 21:18:51 +0000219 parser.add_argument('-i', metavar='FILE', dest='flist',
R. David Murray94f58c32010-12-17 16:29:07 +0000220 help=('add all the files and directories listed in '
Éric Araujo3b371cf2011-09-01 20:00:33 +0200221 'FILE to the list considered for compilation; '
222 'if "-", names are read from stdin'))
R. David Murray94f58c32010-12-17 16:29:07 +0000223 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
224 help=('zero or more file and directory names '
225 'to compile; if no arguments given, defaults '
226 'to the equivalent of -l sys.path'))
Brett Cannonf1a8df02014-09-12 10:39:48 -0400227 parser.add_argument('-j', '--workers', default=1,
228 type=int, help='Run compileall concurrently')
R. David Murray650f1472010-11-20 21:18:51 +0000229
Brett Cannonf1a8df02014-09-12 10:39:48 -0400230 args = parser.parse_args()
R. David Murray95333e32010-12-14 22:32:50 +0000231 compile_dests = args.compile_dest
232
233 if (args.ddir and (len(compile_dests) != 1
234 or not os.path.isdir(compile_dests[0]))):
235 parser.exit('-d destdir requires exactly one directory argument')
R. David Murray650f1472010-11-20 21:18:51 +0000236 if args.rx:
237 import re
238 args.rx = re.compile(args.rx)
239
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500240
241 if args.recursion is not None:
242 maxlevels = args.recursion
243 else:
244 maxlevels = args.maxlevels
245
R. David Murray650f1472010-11-20 21:18:51 +0000246 # if flist is provided then load it
R. David Murray650f1472010-11-20 21:18:51 +0000247 if args.flist:
R. David Murray95333e32010-12-14 22:32:50 +0000248 try:
249 with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
250 for line in f:
251 compile_dests.append(line.strip())
Andrew Svetlov3438fa42012-12-17 23:35:18 +0200252 except OSError:
R. David Murray95333e32010-12-14 22:32:50 +0000253 print("Error reading file list {}".format(args.flist))
254 return False
R. David Murray650f1472010-11-20 21:18:51 +0000255
Brett Cannonf1a8df02014-09-12 10:39:48 -0400256 if args.workers is not None:
257 args.workers = args.workers or None
258
R. David Murray95333e32010-12-14 22:32:50 +0000259 success = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000260 try:
R. David Murray650f1472010-11-20 21:18:51 +0000261 if compile_dests:
262 for dest in compile_dests:
R. David Murray5317e9c2010-12-16 19:08:51 +0000263 if os.path.isfile(dest):
264 if not compile_file(dest, args.ddir, args.force, args.rx,
265 args.quiet, args.legacy):
266 success = False
267 else:
Benjamin Peterson344ff4a2014-08-19 16:13:26 -0500268 if not compile_dir(dest, maxlevels, args.ddir,
R. David Murray650f1472010-11-20 21:18:51 +0000269 args.force, args.rx, args.quiet,
Brett Cannonf1a8df02014-09-12 10:39:48 -0400270 args.legacy, workers=args.workers):
R. David Murray95333e32010-12-14 22:32:50 +0000271 success = False
R. David Murray95333e32010-12-14 22:32:50 +0000272 return success
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000273 else:
R David Murray8a1d1e62013-12-15 20:49:38 -0500274 return compile_path(legacy=args.legacy, force=args.force,
275 quiet=args.quiet)
Guido van Rossumc567b811998-01-19 23:07:55 +0000276 except KeyboardInterrupt:
Éric Araujo2e579f02010-11-20 21:53:02 +0000277 print("\n[interrupted]")
R. David Murray95333e32010-12-14 22:32:50 +0000278 return False
279 return True
R. David Murray650f1472010-11-20 21:18:51 +0000280
Guido van Rossum3bb54481994-08-29 10:52:58 +0000281
282if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000283 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000284 sys.exit(exit_status)