blob: 17cc61dc1a0ca5661b62f7eac16207c925ebcca9 [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
Éric Araujo2e579f02010-11-20 21:53:02 +000015import errno
16import imp
Guido van Rossum3bb54481994-08-29 10:52:58 +000017import py_compile
Brett Cannonbefb14f2009-02-10 02:10:16 +000018import struct
Guido van Rossum3bb54481994-08-29 10:52:58 +000019
Matthias Klosec33b9022010-03-16 00:36:26 +000020__all__ = ["compile_dir","compile_file","compile_path"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000021
Martin v. Löwis5c137c22002-03-18 12:44:08 +000022def compile_dir(dir, maxlevels=10, ddir=None,
Barry Warsaw28a691b2010-04-17 00:19:56 +000023 force=False, rx=None, quiet=False, legacy=False):
Guido van Rossumc567b811998-01-19 23:07:55 +000024 """Byte-compile all modules in the given directory tree.
Guido van Rossum3bb54481994-08-29 10:52:58 +000025
Guido van Rossumc567b811998-01-19 23:07:55 +000026 Arguments (only dir is required):
27
28 dir: the directory to byte-compile
29 maxlevels: maximum recursion level (default 10)
30 ddir: if given, purported directory name (this is the
31 directory name that will show up in error messages)
Barry Warsaw28a691b2010-04-17 00:19:56 +000032 force: if True, force compilation, even if timestamps are up-to-date
33 quiet: if True, be quiet during compilation
34 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Guido van Rossumc567b811998-01-19 23:07:55 +000035 """
Martin v. Löwis5c137c22002-03-18 12:44:08 +000036 if not quiet:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000037 print('Listing', dir, '...')
Guido van Rossumc567b811998-01-19 23:07:55 +000038 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000039 names = os.listdir(dir)
Guido van Rossumc567b811998-01-19 23:07:55 +000040 except os.error:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000041 print("Can't list", dir)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000042 names = []
Guido van Rossumc567b811998-01-19 23:07:55 +000043 names.sort()
Fred Drake9065ea31999-03-29 20:25:40 +000044 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +000045 for name in names:
Barry Warsawc04317f2010-04-26 15:59:03 +000046 if name == '__pycache__':
47 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000048 fullname = os.path.join(dir, name)
Raymond Hettinger8989ea62002-06-01 00:06:20 +000049 if ddir is not None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000050 dfile = os.path.join(ddir, name)
51 else:
52 dfile = None
Matthias Klosec33b9022010-03-16 00:36:26 +000053 if not os.path.isdir(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +000054 if not compile_file(fullname, ddir, force, rx, quiet, legacy):
Matthias Klosec33b9022010-03-16 00:36:26 +000055 success = 0
Éric Araujo2e579f02010-11-20 21:53:02 +000056 elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
57 os.path.isdir(fullname) and not os.path.islink(fullname)):
Brett Cannonbefb14f2009-02-10 02:10:16 +000058 if not compile_dir(fullname, maxlevels - 1, dfile, force, rx,
Barry Warsaw28a691b2010-04-17 00:19:56 +000059 quiet, legacy):
Jeremy Hylton12b64572001-04-18 01:20:21 +000060 success = 0
Fred Drake9065ea31999-03-29 20:25:40 +000061 return success
Guido van Rossumc567b811998-01-19 23:07:55 +000062
Barry Warsaw28a691b2010-04-17 00:19:56 +000063def compile_file(fullname, ddir=None, force=0, rx=None, quiet=False,
64 legacy=False):
Matthias Klosec33b9022010-03-16 00:36:26 +000065 """Byte-compile file.
Barry Warsaw28a691b2010-04-17 00:19:56 +000066 fullname: the file to byte-compile
Matthias Klosec33b9022010-03-16 00:36:26 +000067 ddir: if given, purported directory name (this is the
68 directory name that will show up in error messages)
Barry Warsaw28a691b2010-04-17 00:19:56 +000069 force: if True, force compilation, even if timestamps are up-to-date
70 quiet: if True, be quiet during compilation
71 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Matthias Klosec33b9022010-03-16 00:36:26 +000072 """
73 success = 1
74 name = os.path.basename(fullname)
75 if ddir is not None:
76 dfile = os.path.join(ddir, name)
77 else:
78 dfile = None
79 if rx is not None:
80 mo = rx.search(fullname)
81 if mo:
82 return success
83 if os.path.isfile(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +000084 if legacy:
85 cfile = fullname + ('c' if __debug__ else 'o')
86 else:
87 cfile = imp.cache_from_source(fullname)
88 cache_dir = os.path.dirname(cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +000089 head, tail = name[:-3], name[-3:]
90 if tail == '.py':
91 if not force:
92 try:
93 mtime = int(os.stat(fullname).st_mtime)
94 expect = struct.pack('<4sl', imp.get_magic(), mtime)
Matthias Klosec33b9022010-03-16 00:36:26 +000095 with open(cfile, 'rb') as chandle:
96 actual = chandle.read(8)
97 if expect == actual:
98 return success
99 except IOError:
100 pass
101 if not quiet:
102 print('Compiling', fullname, '...')
103 try:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000104 ok = py_compile.compile(fullname, cfile, dfile, True)
Matthias Klosec33b9022010-03-16 00:36:26 +0000105 except py_compile.PyCompileError as err:
106 if quiet:
107 print('*** Error compiling', fullname, '...')
108 else:
109 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000110 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000111 msg = err.msg.encode(sys.stdout.encoding,
112 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000113 msg = msg.decode(sys.stdout.encoding)
114 print(msg)
Matthias Klosec33b9022010-03-16 00:36:26 +0000115 success = 0
116 except (SyntaxError, UnicodeError, IOError) as e:
117 if quiet:
118 print('*** Error compiling', fullname, '...')
119 else:
120 print('*** ', end='')
121 print(e.__class__.__name__ + ':', e)
122 success = 0
123 else:
124 if ok == 0:
125 success = 0
126 return success
127
Barry Warsaw28a691b2010-04-17 00:19:56 +0000128def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=False,
129 legacy=False):
Guido van Rossumc567b811998-01-19 23:07:55 +0000130 """Byte-compile all module on sys.path.
131
132 Arguments (all optional):
133
134 skip_curdir: if true, skip current directory (default true)
135 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136 force: as for compile_dir() (default False)
137 quiet: as for compile_dir() (default False)
138 legacy: as for compile_dir() (default False)
Guido van Rossumc567b811998-01-19 23:07:55 +0000139 """
Fred Drake9065ea31999-03-29 20:25:40 +0000140 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +0000141 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000142 if (not dir or dir == os.curdir) and skip_curdir:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000143 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000144 else:
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000145 success = success and compile_dir(dir, maxlevels, None,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000146 force, quiet=quiet,
147 legacy=legacy)
Fred Drake9065ea31999-03-29 20:25:40 +0000148 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000149
Matthias Klosec33b9022010-03-16 00:36:26 +0000150
Guido van Rossum3bb54481994-08-29 10:52:58 +0000151def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000152 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000153 import argparse
154
155 parser = argparse.ArgumentParser(
156 description='Utilities to support installing Python libraries.')
157 parser.add_argument('-l', action='store_const', default=10, const=0,
158 dest='maxlevels', help="don't recurse down")
159 parser.add_argument('-f', action='store_true', dest='force',
160 help='force rebuild even if timestamps are up to date')
161 parser.add_argument('-q', action='store_true', dest='quiet',
Éric Araujo2e579f02010-11-20 21:53:02 +0000162 help='reduce output')
R. David Murray650f1472010-11-20 21:18:51 +0000163 parser.add_argument('-b', action='store_true', dest='legacy',
Éric Araujo2e579f02010-11-20 21:53:02 +0000164 help='produce legacy byte-compiled file paths')
R. David Murray650f1472010-11-20 21:18:51 +0000165 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
166 help=('purported directory name for error messages; '
167 'if no directory arguments, -l sys.path '
168 'is assumed.'))
169 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
170 help=('skip files matching the regular expression.\n\t'
Éric Araujo2e579f02010-11-20 21:53:02 +0000171 'The regexp is searched for in the full path '
R. David Murray650f1472010-11-20 21:18:51 +0000172 'of the file'))
173 parser.add_argument('-i', metavar='FILE', dest='flist',
Éric Araujo2e579f02010-11-20 21:53:02 +0000174 help='expand the list with the content of FILE.')
R. David Murray650f1472010-11-20 21:18:51 +0000175 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='?')
176 args = parser.parse_args()
177
178 if (args.ddir and args.compile_dest != 1 and
179 not os.path.isdir(args.compile_dest)):
Éric Araujo2e579f02010-11-20 21:53:02 +0000180 raise argparse.ArgumentError(
181 "-d destdir requires exactly one directory argument")
R. David Murray650f1472010-11-20 21:18:51 +0000182 if args.rx:
183 import re
184 args.rx = re.compile(args.rx)
185
186 # if flist is provided then load it
187 compile_dests = [args.compile_dest]
188 if args.flist:
189 with open(args.flist) as f:
190 files = f.read().split()
191 compile_dests.extend(files)
192
Guido van Rossumc567b811998-01-19 23:07:55 +0000193 try:
R. David Murray650f1472010-11-20 21:18:51 +0000194 if compile_dests:
195 for dest in compile_dests:
196 if os.path.isdir(dest):
197 if not compile_dir(dest, args.maxlevels, args.ddir,
198 args.force, args.rx, args.quiet,
199 args.legacy):
200 return 0
201 else:
202 if not compile_file(dest, args.ddir, args.force, args.rx,
203 args.quiet, args.legacy):
204 return 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000205 else:
R. David Murray650f1472010-11-20 21:18:51 +0000206 return compile_path(legacy=args.legacy)
Guido van Rossumc567b811998-01-19 23:07:55 +0000207 except KeyboardInterrupt:
Éric Araujo2e579f02010-11-20 21:53:02 +0000208 print("\n[interrupted]")
R. David Murray650f1472010-11-20 21:18:51 +0000209 return 0
210 return 1
211
Guido van Rossum3bb54481994-08-29 10:52:58 +0000212
213if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000214 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000215 sys.exit(exit_status)