blob: d9d78161cc33891a7df4b4115d033d96adc8c04d [file] [log] [blame]
Guido van Rossumc567b811998-01-19 23:07:55 +00001"""Module/script to "compile" all .py files to .pyc (or .pyo) file.
2
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.
12
13"""
Guido van Rossum3bb54481994-08-29 10:52:58 +000014import os
Barry Warsaw28a691b2010-04-17 00:19:56 +000015import errno
Guido van Rossum3bb54481994-08-29 10:52:58 +000016import sys
17import py_compile
Brett Cannonbefb14f2009-02-10 02:10:16 +000018import struct
19import imp
Guido van Rossum3bb54481994-08-29 10:52:58 +000020
Matthias Klosec33b9022010-03-16 00:36:26 +000021__all__ = ["compile_dir","compile_file","compile_path"]
Skip Montanaroe99d5ea2001-01-20 19:54:20 +000022
Martin v. Löwis5c137c22002-03-18 12:44:08 +000023def compile_dir(dir, maxlevels=10, ddir=None,
Barry Warsaw28a691b2010-04-17 00:19:56 +000024 force=False, rx=None, quiet=False, legacy=False):
Guido van Rossumc567b811998-01-19 23:07:55 +000025 """Byte-compile all modules in the given directory tree.
Guido van Rossum3bb54481994-08-29 10:52:58 +000026
Guido van Rossumc567b811998-01-19 23:07:55 +000027 Arguments (only dir is required):
28
29 dir: the directory to byte-compile
30 maxlevels: maximum recursion level (default 10)
31 ddir: if given, purported directory name (this is the
32 directory name that will show up in error messages)
Barry Warsaw28a691b2010-04-17 00:19:56 +000033 force: if True, force compilation, even if timestamps are up-to-date
34 quiet: if True, be quiet during compilation
35 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Guido van Rossumc567b811998-01-19 23:07:55 +000036
37 """
Martin v. Löwis5c137c22002-03-18 12:44:08 +000038 if not quiet:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000039 print('Listing', dir, '...')
Guido van Rossumc567b811998-01-19 23:07:55 +000040 try:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000041 names = os.listdir(dir)
Guido van Rossumc567b811998-01-19 23:07:55 +000042 except os.error:
Guido van Rossumbe19ed72007-02-09 05:37:30 +000043 print("Can't list", dir)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000044 names = []
Guido van Rossumc567b811998-01-19 23:07:55 +000045 names.sort()
Fred Drake9065ea31999-03-29 20:25:40 +000046 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +000047 for name in names:
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
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000056 elif maxlevels > 0 and \
57 name != os.curdir and name != os.pardir and \
58 os.path.isdir(fullname) and \
59 not os.path.islink(fullname):
Brett Cannonbefb14f2009-02-10 02:10:16 +000060 if not compile_dir(fullname, maxlevels - 1, dfile, force, rx,
Barry Warsaw28a691b2010-04-17 00:19:56 +000061 quiet, legacy):
Jeremy Hylton12b64572001-04-18 01:20:21 +000062 success = 0
Fred Drake9065ea31999-03-29 20:25:40 +000063 return success
Guido van Rossumc567b811998-01-19 23:07:55 +000064
Barry Warsaw28a691b2010-04-17 00:19:56 +000065def compile_file(fullname, ddir=None, force=0, rx=None, quiet=False,
66 legacy=False):
Matthias Klosec33b9022010-03-16 00:36:26 +000067 """Byte-compile file.
Barry Warsaw28a691b2010-04-17 00:19:56 +000068 fullname: the file to byte-compile
Matthias Klosec33b9022010-03-16 00:36:26 +000069 ddir: if given, purported directory name (this is the
70 directory name that will show up in error messages)
Barry Warsaw28a691b2010-04-17 00:19:56 +000071 force: if True, force compilation, even if timestamps are up-to-date
72 quiet: if True, be quiet during compilation
73 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Matthias Klosec33b9022010-03-16 00:36:26 +000074
75 """
76 success = 1
77 name = os.path.basename(fullname)
78 if ddir is not None:
79 dfile = os.path.join(ddir, name)
80 else:
81 dfile = None
82 if rx is not None:
83 mo = rx.search(fullname)
84 if mo:
85 return success
86 if os.path.isfile(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +000087 if legacy:
88 cfile = fullname + ('c' if __debug__ else 'o')
89 else:
90 cfile = imp.cache_from_source(fullname)
91 cache_dir = os.path.dirname(cfile)
92 try:
93 os.mkdir(cache_dir)
94 except OSError as error:
95 if error.errno != errno.EEXIST:
96 raise
Matthias Klosec33b9022010-03-16 00:36:26 +000097 head, tail = name[:-3], name[-3:]
98 if tail == '.py':
99 if not force:
100 try:
101 mtime = int(os.stat(fullname).st_mtime)
102 expect = struct.pack('<4sl', imp.get_magic(), mtime)
Matthias Klosec33b9022010-03-16 00:36:26 +0000103 with open(cfile, 'rb') as chandle:
104 actual = chandle.read(8)
105 if expect == actual:
106 return success
107 except IOError:
108 pass
109 if not quiet:
110 print('Compiling', fullname, '...')
111 try:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000112 ok = py_compile.compile(fullname, cfile, dfile, True)
Matthias Klosec33b9022010-03-16 00:36:26 +0000113 except py_compile.PyCompileError as err:
114 if quiet:
115 print('*** Error compiling', fullname, '...')
116 else:
117 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000118 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000119 msg = err.msg.encode(sys.stdout.encoding,
120 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000121 msg = msg.decode(sys.stdout.encoding)
122 print(msg)
Matthias Klosec33b9022010-03-16 00:36:26 +0000123 success = 0
124 except (SyntaxError, UnicodeError, IOError) as e:
125 if quiet:
126 print('*** Error compiling', fullname, '...')
127 else:
128 print('*** ', end='')
129 print(e.__class__.__name__ + ':', e)
130 success = 0
131 else:
132 if ok == 0:
133 success = 0
134 return success
135
Barry Warsaw28a691b2010-04-17 00:19:56 +0000136def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=False,
137 legacy=False):
Guido van Rossumc567b811998-01-19 23:07:55 +0000138 """Byte-compile all module on sys.path.
139
140 Arguments (all optional):
141
142 skip_curdir: if true, skip current directory (default true)
143 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000144 force: as for compile_dir() (default False)
145 quiet: as for compile_dir() (default False)
146 legacy: as for compile_dir() (default False)
Guido van Rossumc567b811998-01-19 23:07:55 +0000147
148 """
Fred Drake9065ea31999-03-29 20:25:40 +0000149 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +0000150 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 if (not dir or dir == os.curdir) and skip_curdir:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000152 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000153 else:
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000154 success = success and compile_dir(dir, maxlevels, None,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000155 force, quiet=quiet,
156 legacy=legacy)
Fred Drake9065ea31999-03-29 20:25:40 +0000157 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000158
Matthias Klosec33b9022010-03-16 00:36:26 +0000159def expand_args(args, flist):
160 """read names in flist and append to args"""
161 expanded = args[:]
162 if flist:
163 try:
164 if flist == '-':
165 fd = sys.stdin
166 else:
167 fd = open(flist)
168 while 1:
169 line = fd.readline()
170 if not line:
171 break
172 expanded.append(line[:-1])
173 except IOError:
174 print("Error reading file list %s" % flist)
175 raise
176 return expanded
177
Guido van Rossum3bb54481994-08-29 10:52:58 +0000178def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000179 """Script main program."""
180 import getopt
181 try:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000182 opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:i:b')
Guido van Rossumb940e112007-01-10 16:19:56 +0000183 except getopt.error as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000184 print(msg)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000185 print("usage: python compileall.py [-l] [-f] [-q] [-d destdir] "
Matthias Klosec33b9022010-03-16 00:36:26 +0000186 "[-x regexp] [-i list] [directory|file ...]")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000187 print("-l: don't recurse down")
188 print("-f: force rebuild even if timestamps are up-to-date")
189 print("-q: quiet operation")
190 print("-d destdir: purported directory name for error messages")
191 print(" if no directory arguments, -l sys.path is assumed")
192 print("-x regexp: skip files matching the regular expression regexp")
Christian Heimes78644762008-03-04 23:39:23 +0000193 print(" the regexp is searched for in the full path of the file")
Barry Warsaw28a691b2010-04-17 00:19:56 +0000194 print("-i list: expand list with its content "
195 "(file and directory names)")
196 print("-b: Produce legacy byte-compile file paths")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000197 sys.exit(2)
Guido van Rossumc567b811998-01-19 23:07:55 +0000198 maxlevels = 10
199 ddir = None
Barry Warsaw28a691b2010-04-17 00:19:56 +0000200 force = False
201 quiet = False
Jeremy Hylton12b64572001-04-18 01:20:21 +0000202 rx = None
Matthias Klosec33b9022010-03-16 00:36:26 +0000203 flist = None
Barry Warsaw28a691b2010-04-17 00:19:56 +0000204 legacy = False
Guido van Rossumc567b811998-01-19 23:07:55 +0000205 for o, a in opts:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 if o == '-l': maxlevels = 0
207 if o == '-d': ddir = a
Barry Warsaw28a691b2010-04-17 00:19:56 +0000208 if o == '-f': force = True
209 if o == '-q': quiet = True
Jeremy Hylton12b64572001-04-18 01:20:21 +0000210 if o == '-x':
211 import re
212 rx = re.compile(a)
Matthias Klosec33b9022010-03-16 00:36:26 +0000213 if o == '-i': flist = a
Barry Warsaw28a691b2010-04-17 00:19:56 +0000214 if o == '-b': legacy = True
Guido van Rossumc567b811998-01-19 23:07:55 +0000215 if ddir:
Matthias Klosec33b9022010-03-16 00:36:26 +0000216 if len(args) != 1 and not os.path.isdir(args[0]):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000217 print("-d destdir require exactly one directory argument")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000218 sys.exit(2)
Fred Drake9065ea31999-03-29 20:25:40 +0000219 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +0000220 try:
Matthias Klosec33b9022010-03-16 00:36:26 +0000221 if args or flist:
222 try:
223 if flist:
224 args = expand_args(args, flist)
225 except IOError:
226 success = 0
227 if success:
228 for arg in args:
229 if os.path.isdir(arg):
230 if not compile_dir(arg, maxlevels, ddir,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000231 force, rx, quiet, legacy):
Matthias Klosec33b9022010-03-16 00:36:26 +0000232 success = 0
233 else:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000234 if not compile_file(arg, ddir, force, rx,
235 quiet, legacy):
Matthias Klosec33b9022010-03-16 00:36:26 +0000236 success = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 else:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000238 success = compile_path(legacy=legacy)
Guido van Rossumc567b811998-01-19 23:07:55 +0000239 except KeyboardInterrupt:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000240 print("\n[interrupt]")
Fred Drake9065ea31999-03-29 20:25:40 +0000241 success = 0
242 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000243
244if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000245 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000246 sys.exit(exit_status)