blob: ae86292790f0294a865137471edffa25acffaf24 [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
15import sys
16import py_compile
Brett Cannonbefb14f2009-02-10 02:10:16 +000017import struct
18import imp
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,
23 force=0, rx=None, quiet=0):
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)
Guido van Rossum0b56a3e1998-12-21 18:23:38 +000032 force: if 1, force compilation, even if timestamps are up-to-date
Martin v. Löwis5c137c22002-03-18 12:44:08 +000033 quiet: if 1, be quiet during compilation
Guido van Rossumc567b811998-01-19 23:07:55 +000034
35 """
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:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000046 fullname = os.path.join(dir, name)
Raymond Hettinger8989ea62002-06-01 00:06:20 +000047 if ddir is not None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000048 dfile = os.path.join(ddir, name)
49 else:
50 dfile = None
Matthias Klosec33b9022010-03-16 00:36:26 +000051 if not os.path.isdir(fullname):
52 if not compile_file(fullname, ddir, force, rx, quiet):
53 success = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000054 elif maxlevels > 0 and \
55 name != os.curdir and name != os.pardir and \
56 os.path.isdir(fullname) and \
57 not os.path.islink(fullname):
Brett Cannonbefb14f2009-02-10 02:10:16 +000058 if not compile_dir(fullname, maxlevels - 1, dfile, force, rx,
59 quiet):
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
Matthias Klosec33b9022010-03-16 00:36:26 +000063def compile_file(fullname, ddir=None, force=0, rx=None, quiet=0):
64 """Byte-compile file.
65 file: the file to byte-compile
66 ddir: if given, purported directory name (this is the
67 directory name that will show up in error messages)
68 force: if 1, force compilation, even if timestamps are up-to-date
69 quiet: if 1, be quiet during compilation
70
71 """
72 success = 1
73 name = os.path.basename(fullname)
74 if ddir is not None:
75 dfile = os.path.join(ddir, name)
76 else:
77 dfile = None
78 if rx is not None:
79 mo = rx.search(fullname)
80 if mo:
81 return success
82 if os.path.isfile(fullname):
83 head, tail = name[:-3], name[-3:]
84 if tail == '.py':
85 if not force:
86 try:
87 mtime = int(os.stat(fullname).st_mtime)
88 expect = struct.pack('<4sl', imp.get_magic(), mtime)
89 cfile = fullname + (__debug__ and 'c' or 'o')
90 with open(cfile, 'rb') as chandle:
91 actual = chandle.read(8)
92 if expect == actual:
93 return success
94 except IOError:
95 pass
96 if not quiet:
97 print('Compiling', fullname, '...')
98 try:
99 ok = py_compile.compile(fullname, None, dfile, True)
Matthias Klosec33b9022010-03-16 00:36:26 +0000100 except py_compile.PyCompileError as err:
101 if quiet:
102 print('*** Error compiling', fullname, '...')
103 else:
104 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000105 # escape non-printable characters in msg
106 msg = err.msg.encode(sys.stdout.encoding, errors='backslashreplace')
107 msg = msg.decode(sys.stdout.encoding)
108 print(msg)
Matthias Klosec33b9022010-03-16 00:36:26 +0000109 success = 0
110 except (SyntaxError, UnicodeError, IOError) as e:
111 if quiet:
112 print('*** Error compiling', fullname, '...')
113 else:
114 print('*** ', end='')
115 print(e.__class__.__name__ + ':', e)
116 success = 0
117 else:
118 if ok == 0:
119 success = 0
120 return success
121
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000122def compile_path(skip_curdir=1, maxlevels=0, force=0, quiet=0):
Guido van Rossumc567b811998-01-19 23:07:55 +0000123 """Byte-compile all module on sys.path.
124
125 Arguments (all optional):
126
127 skip_curdir: if true, skip current directory (default true)
128 maxlevels: max recursion level (default 0)
Guido van Rossum0b56a3e1998-12-21 18:23:38 +0000129 force: as for compile_dir() (default 0)
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000130 quiet: as for compile_dir() (default 0)
Guido van Rossumc567b811998-01-19 23:07:55 +0000131
132 """
Fred Drake9065ea31999-03-29 20:25:40 +0000133 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +0000134 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000135 if (not dir or dir == os.curdir) and skip_curdir:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000136 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000137 else:
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000138 success = success and compile_dir(dir, maxlevels, None,
139 force, quiet=quiet)
Fred Drake9065ea31999-03-29 20:25:40 +0000140 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000141
Matthias Klosec33b9022010-03-16 00:36:26 +0000142def expand_args(args, flist):
143 """read names in flist and append to args"""
144 expanded = args[:]
145 if flist:
146 try:
147 if flist == '-':
148 fd = sys.stdin
149 else:
150 fd = open(flist)
151 while 1:
152 line = fd.readline()
153 if not line:
154 break
155 expanded.append(line[:-1])
156 except IOError:
157 print("Error reading file list %s" % flist)
158 raise
159 return expanded
160
Guido van Rossum3bb54481994-08-29 10:52:58 +0000161def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000162 """Script main program."""
163 import getopt
164 try:
Matthias Klosec33b9022010-03-16 00:36:26 +0000165 opts, args = getopt.getopt(sys.argv[1:], 'lfqd:x:i:')
Guido van Rossumb940e112007-01-10 16:19:56 +0000166 except getopt.error as msg:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000167 print(msg)
168 print("usage: python compileall.py [-l] [-f] [-q] [-d destdir] " \
Matthias Klosec33b9022010-03-16 00:36:26 +0000169 "[-x regexp] [-i list] [directory|file ...]")
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000170 print("-l: don't recurse down")
171 print("-f: force rebuild even if timestamps are up-to-date")
172 print("-q: quiet operation")
173 print("-d destdir: purported directory name for error messages")
174 print(" if no directory arguments, -l sys.path is assumed")
175 print("-x regexp: skip files matching the regular expression regexp")
Christian Heimes78644762008-03-04 23:39:23 +0000176 print(" the regexp is searched for in the full path of the file")
Matthias Klosec33b9022010-03-16 00:36:26 +0000177 print("-i list: expand list with its content (file and directory names)")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 sys.exit(2)
Guido van Rossumc567b811998-01-19 23:07:55 +0000179 maxlevels = 10
180 ddir = None
Guido van Rossum0b56a3e1998-12-21 18:23:38 +0000181 force = 0
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000182 quiet = 0
Jeremy Hylton12b64572001-04-18 01:20:21 +0000183 rx = None
Matthias Klosec33b9022010-03-16 00:36:26 +0000184 flist = None
Guido van Rossumc567b811998-01-19 23:07:55 +0000185 for o, a in opts:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000186 if o == '-l': maxlevels = 0
187 if o == '-d': ddir = a
Guido van Rossum0b56a3e1998-12-21 18:23:38 +0000188 if o == '-f': force = 1
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000189 if o == '-q': quiet = 1
Jeremy Hylton12b64572001-04-18 01:20:21 +0000190 if o == '-x':
191 import re
192 rx = re.compile(a)
Matthias Klosec33b9022010-03-16 00:36:26 +0000193 if o == '-i': flist = a
Guido van Rossumc567b811998-01-19 23:07:55 +0000194 if ddir:
Matthias Klosec33b9022010-03-16 00:36:26 +0000195 if len(args) != 1 and not os.path.isdir(args[0]):
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000196 print("-d destdir require exactly one directory argument")
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000197 sys.exit(2)
Fred Drake9065ea31999-03-29 20:25:40 +0000198 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +0000199 try:
Matthias Klosec33b9022010-03-16 00:36:26 +0000200 if args or flist:
201 try:
202 if flist:
203 args = expand_args(args, flist)
204 except IOError:
205 success = 0
206 if success:
207 for arg in args:
208 if os.path.isdir(arg):
209 if not compile_dir(arg, maxlevels, ddir,
210 force, rx, quiet):
211 success = 0
212 else:
213 if not compile_file(arg, ddir, force, rx, quiet):
214 success = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000215 else:
Fred Drake9065ea31999-03-29 20:25:40 +0000216 success = compile_path()
Guido van Rossumc567b811998-01-19 23:07:55 +0000217 except KeyboardInterrupt:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000218 print("\n[interrupt]")
Fred Drake9065ea31999-03-29 20:25:40 +0000219 success = 0
220 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000221
222if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000223 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000224 sys.exit(exit_status)