blob: ade5afb75c994ceaf6a5bfb0345828550af7bf32 [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:
Barry Warsawc04317f2010-04-26 15:59:03 +000048 if name == '__pycache__':
49 continue
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000050 fullname = os.path.join(dir, name)
Raymond Hettinger8989ea62002-06-01 00:06:20 +000051 if ddir is not None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000052 dfile = os.path.join(ddir, name)
53 else:
54 dfile = None
Matthias Klosec33b9022010-03-16 00:36:26 +000055 if not os.path.isdir(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +000056 if not compile_file(fullname, ddir, force, rx, quiet, legacy):
Matthias Klosec33b9022010-03-16 00:36:26 +000057 success = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000058 elif maxlevels > 0 and \
59 name != os.curdir and name != os.pardir and \
60 os.path.isdir(fullname) and \
61 not os.path.islink(fullname):
Brett Cannonbefb14f2009-02-10 02:10:16 +000062 if not compile_dir(fullname, maxlevels - 1, dfile, force, rx,
Barry Warsaw28a691b2010-04-17 00:19:56 +000063 quiet, legacy):
Jeremy Hylton12b64572001-04-18 01:20:21 +000064 success = 0
Fred Drake9065ea31999-03-29 20:25:40 +000065 return success
Guido van Rossumc567b811998-01-19 23:07:55 +000066
Barry Warsaw28a691b2010-04-17 00:19:56 +000067def compile_file(fullname, ddir=None, force=0, rx=None, quiet=False,
68 legacy=False):
Matthias Klosec33b9022010-03-16 00:36:26 +000069 """Byte-compile file.
Barry Warsaw28a691b2010-04-17 00:19:56 +000070 fullname: the file to byte-compile
Matthias Klosec33b9022010-03-16 00:36:26 +000071 ddir: if given, purported directory name (this is the
72 directory name that will show up in error messages)
Barry Warsaw28a691b2010-04-17 00:19:56 +000073 force: if True, force compilation, even if timestamps are up-to-date
74 quiet: if True, be quiet during compilation
75 legacy: if True, produce legacy pyc paths instead of PEP 3147 paths
Matthias Klosec33b9022010-03-16 00:36:26 +000076
77 """
78 success = 1
79 name = os.path.basename(fullname)
80 if ddir is not None:
81 dfile = os.path.join(ddir, name)
82 else:
83 dfile = None
84 if rx is not None:
85 mo = rx.search(fullname)
86 if mo:
87 return success
88 if os.path.isfile(fullname):
Barry Warsaw28a691b2010-04-17 00:19:56 +000089 if legacy:
90 cfile = fullname + ('c' if __debug__ else 'o')
91 else:
92 cfile = imp.cache_from_source(fullname)
93 cache_dir = os.path.dirname(cfile)
Matthias Klosec33b9022010-03-16 00:36:26 +000094 head, tail = name[:-3], name[-3:]
95 if tail == '.py':
96 if not force:
97 try:
98 mtime = int(os.stat(fullname).st_mtime)
99 expect = struct.pack('<4sl', imp.get_magic(), mtime)
Matthias Klosec33b9022010-03-16 00:36:26 +0000100 with open(cfile, 'rb') as chandle:
101 actual = chandle.read(8)
102 if expect == actual:
103 return success
104 except IOError:
105 pass
106 if not quiet:
107 print('Compiling', fullname, '...')
108 try:
Barry Warsaw28a691b2010-04-17 00:19:56 +0000109 ok = py_compile.compile(fullname, cfile, dfile, True)
Matthias Klosec33b9022010-03-16 00:36:26 +0000110 except py_compile.PyCompileError as err:
111 if quiet:
112 print('*** Error compiling', fullname, '...')
113 else:
114 print('*** ', end='')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000115 # escape non-printable characters in msg
Barry Warsaw28a691b2010-04-17 00:19:56 +0000116 msg = err.msg.encode(sys.stdout.encoding,
117 errors='backslashreplace')
Martin v. Löwis4b003072010-03-16 13:19:21 +0000118 msg = msg.decode(sys.stdout.encoding)
119 print(msg)
Matthias Klosec33b9022010-03-16 00:36:26 +0000120 success = 0
121 except (SyntaxError, UnicodeError, IOError) as e:
122 if quiet:
123 print('*** Error compiling', fullname, '...')
124 else:
125 print('*** ', end='')
126 print(e.__class__.__name__ + ':', e)
127 success = 0
128 else:
129 if ok == 0:
130 success = 0
131 return success
132
Barry Warsaw28a691b2010-04-17 00:19:56 +0000133def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=False,
134 legacy=False):
Guido van Rossumc567b811998-01-19 23:07:55 +0000135 """Byte-compile all module on sys.path.
136
137 Arguments (all optional):
138
139 skip_curdir: if true, skip current directory (default true)
140 maxlevels: max recursion level (default 0)
Barry Warsaw28a691b2010-04-17 00:19:56 +0000141 force: as for compile_dir() (default False)
142 quiet: as for compile_dir() (default False)
143 legacy: as for compile_dir() (default False)
Guido van Rossumc567b811998-01-19 23:07:55 +0000144
145 """
Fred Drake9065ea31999-03-29 20:25:40 +0000146 success = 1
Guido van Rossumc567b811998-01-19 23:07:55 +0000147 for dir in sys.path:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000148 if (not dir or dir == os.curdir) and skip_curdir:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000149 print('Skipping current directory')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000150 else:
Martin v. Löwis5c137c22002-03-18 12:44:08 +0000151 success = success and compile_dir(dir, maxlevels, None,
Barry Warsaw28a691b2010-04-17 00:19:56 +0000152 force, quiet=quiet,
153 legacy=legacy)
Fred Drake9065ea31999-03-29 20:25:40 +0000154 return success
Guido van Rossum3bb54481994-08-29 10:52:58 +0000155
Matthias Klosec33b9022010-03-16 00:36:26 +0000156
Guido van Rossum3bb54481994-08-29 10:52:58 +0000157def main():
Guido van Rossumc567b811998-01-19 23:07:55 +0000158 """Script main program."""
R. David Murray650f1472010-11-20 21:18:51 +0000159 import argparse
160
161 parser = argparse.ArgumentParser(
162 description='Utilities to support installing Python libraries.')
163 parser.add_argument('-l', action='store_const', default=10, const=0,
164 dest='maxlevels', help="don't recurse down")
165 parser.add_argument('-f', action='store_true', dest='force',
166 help='force rebuild even if timestamps are up to date')
167 parser.add_argument('-q', action='store_true', dest='quiet',
168 help='quiet operation')
169 parser.add_argument('-b', action='store_true', dest='legacy',
170 help='procude legacy byte-compiled file paths')
171 parser.add_argument('-d', metavar='DESTDIR', dest='ddir', default=None,
172 help=('purported directory name for error messages; '
173 'if no directory arguments, -l sys.path '
174 'is assumed.'))
175 parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
176 help=('skip files matching the regular expression.\n\t'
177 'The regexp is searched for in the full path'
178 'of the file'))
179 parser.add_argument('-i', metavar='FILE', dest='flist',
180 help='expand the list with the contenent of FILE.')
181 parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='?')
182 args = parser.parse_args()
183
184 if (args.ddir and args.compile_dest != 1 and
185 not os.path.isdir(args.compile_dest)):
186 raise argparse.ArgumentError("-d destdir require exactly one "
187 "directory argument")
188 if args.rx:
189 import re
190 args.rx = re.compile(args.rx)
191
192 # if flist is provided then load it
193 compile_dests = [args.compile_dest]
194 if args.flist:
195 with open(args.flist) as f:
196 files = f.read().split()
197 compile_dests.extend(files)
198
Guido van Rossumc567b811998-01-19 23:07:55 +0000199 try:
R. David Murray650f1472010-11-20 21:18:51 +0000200 if compile_dests:
201 for dest in compile_dests:
202 if os.path.isdir(dest):
203 if not compile_dir(dest, args.maxlevels, args.ddir,
204 args.force, args.rx, args.quiet,
205 args.legacy):
206 return 0
207 else:
208 if not compile_file(dest, args.ddir, args.force, args.rx,
209 args.quiet, args.legacy):
210 return 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000211 else:
R. David Murray650f1472010-11-20 21:18:51 +0000212 return compile_path(legacy=args.legacy)
Guido van Rossumc567b811998-01-19 23:07:55 +0000213 except KeyboardInterrupt:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000214 print("\n[interrupt]")
R. David Murray650f1472010-11-20 21:18:51 +0000215 return 0
216 return 1
217
Guido van Rossum3bb54481994-08-29 10:52:58 +0000218
219if __name__ == '__main__':
Raymond Hettinger7b4b7882004-12-20 00:29:29 +0000220 exit_status = int(not main())
Jeremy Hylton12b64572001-04-18 01:20:21 +0000221 sys.exit(exit_status)