compileall.py 9.44 KB
Newer Older
1
"""Module/script to byte-compile all .py files to .pyc (or .pyo) files.
2 3 4 5 6 7 8 9 10 11 12

When called as a script with arguments, this compiles the directories
given as arguments recursively; the -l option prevents it from
recursing into directories.

Without arguments, if compiles all modules on sys.path, without
recursing into subdirectories.  (Even though it should do so for
packages -- for now, you'll have to deal with packages separately.)

See module py_compile for details of the actual byte-compilation.
"""
13 14
import os
import sys
15 16
import errno
import imp
17
import py_compile
18
import struct
19

20
__all__ = ["compile_dir","compile_file","compile_path"]
21

22 23
def compile_dir(dir, maxlevels=10, ddir=None, force=False, rx=None,
                quiet=False, legacy=False, optimize=-1):
24 25 26 27 28 29
    """Byte-compile all modules in the given directory tree.

    Arguments (only dir is required):

    dir:       the directory to byte-compile
    maxlevels: maximum recursion level (default 10)
30 31
    ddir:      the directory that will be prepended to the path to the
               file as it is compiled into each byte-code file.
Barry Warsaw's avatar
Barry Warsaw committed
32 33 34
    force:     if True, force compilation, even if timestamps are up-to-date
    quiet:     if True, be quiet during compilation
    legacy:    if True, produce legacy pyc paths instead of PEP 3147 paths
35
    optimize:  optimization level or -1 for level of the interpreter
36
    """
37
    if not quiet:
38
        print('Listing {!r}...'.format(dir))
39
    try:
40
        names = os.listdir(dir)
41
    except OSError:
42
        print("Can't list {!r}".format(dir))
43
        names = []
44
    names.sort()
45
    success = 1
46
    for name in names:
47 48
        if name == '__pycache__':
            continue
49
        fullname = os.path.join(dir, name)
50
        if ddir is not None:
51 52 53
            dfile = os.path.join(ddir, name)
        else:
            dfile = None
54
        if not os.path.isdir(fullname):
55 56
            if not compile_file(fullname, ddir, force, rx, quiet,
                                legacy, optimize):
57
                success = 0
58 59
        elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
              os.path.isdir(fullname) and not os.path.islink(fullname)):
60
            if not compile_dir(fullname, maxlevels - 1, dfile, force, rx,
61
                               quiet, legacy, optimize):
62
                success = 0
63
    return success
64

65
def compile_file(fullname, ddir=None, force=False, rx=None, quiet=False,
66
                 legacy=False, optimize=-1):
67 68 69 70
    """Byte-compile one file.

    Arguments (only fullname is required):

Barry Warsaw's avatar
Barry Warsaw committed
71
    fullname:  the file to byte-compile
72 73
    ddir:      if given, the directory name compiled in to the
               byte-code file.
Barry Warsaw's avatar
Barry Warsaw committed
74 75 76
    force:     if True, force compilation, even if timestamps are up-to-date
    quiet:     if True, be quiet during compilation
    legacy:    if True, produce legacy pyc paths instead of PEP 3147 paths
77
    optimize:  optimization level or -1 for level of the interpreter
78 79 80 81 82 83 84 85 86 87 88 89
    """
    success = 1
    name = os.path.basename(fullname)
    if ddir is not None:
        dfile = os.path.join(ddir, name)
    else:
        dfile = None
    if rx is not None:
        mo = rx.search(fullname)
        if mo:
            return success
    if os.path.isfile(fullname):
Barry Warsaw's avatar
Barry Warsaw committed
90 91 92
        if legacy:
            cfile = fullname + ('c' if __debug__ else 'o')
        else:
93 94 95 96 97
            if optimize >= 0:
                cfile = imp.cache_from_source(fullname,
                                              debug_override=not optimize)
            else:
                cfile = imp.cache_from_source(fullname)
Barry Warsaw's avatar
Barry Warsaw committed
98
            cache_dir = os.path.dirname(cfile)
99 100 101 102 103 104 105 106 107 108
        head, tail = name[:-3], name[-3:]
        if tail == '.py':
            if not force:
                try:
                    mtime = int(os.stat(fullname).st_mtime)
                    expect = struct.pack('<4sl', imp.get_magic(), mtime)
                    with open(cfile, 'rb') as chandle:
                        actual = chandle.read(8)
                    if expect == actual:
                        return success
109
                except OSError:
110 111
                    pass
            if not quiet:
112
                print('Compiling {!r}...'.format(fullname))
113
            try:
114 115
                ok = py_compile.compile(fullname, cfile, dfile, True,
                                        optimize=optimize)
116 117
            except py_compile.PyCompileError as err:
                if quiet:
118
                    print('*** Error compiling {!r}...'.format(fullname))
119 120
                else:
                    print('*** ', end='')
121
                # escape non-printable characters in msg
Barry Warsaw's avatar
Barry Warsaw committed
122 123
                msg = err.msg.encode(sys.stdout.encoding,
                                     errors='backslashreplace')
124 125
                msg = msg.decode(sys.stdout.encoding)
                print(msg)
126
                success = 0
127
            except (SyntaxError, UnicodeError, OSError) as e:
128
                if quiet:
129
                    print('*** Error compiling {!r}...'.format(fullname))
130 131 132 133 134 135 136 137 138
                else:
                    print('*** ', end='')
                print(e.__class__.__name__ + ':', e)
                success = 0
            else:
                if ok == 0:
                    success = 0
    return success

Barry Warsaw's avatar
Barry Warsaw committed
139
def compile_path(skip_curdir=1, maxlevels=0, force=False, quiet=False,
140
                 legacy=False, optimize=-1):
141 142 143 144
    """Byte-compile all module on sys.path.

    Arguments (all optional):

145
    skip_curdir: if true, skip current directory (default True)
146
    maxlevels:   max recursion level (default 0)
Barry Warsaw's avatar
Barry Warsaw committed
147 148 149
    force: as for compile_dir() (default False)
    quiet: as for compile_dir() (default False)
    legacy: as for compile_dir() (default False)
150
    optimize: as for compile_dir() (default -1)
151
    """
152
    success = 1
153
    for dir in sys.path:
154
        if (not dir or dir == os.curdir) and skip_curdir:
155
            print('Skipping current directory')
156
        else:
157
            success = success and compile_dir(dir, maxlevels, None,
Barry Warsaw's avatar
Barry Warsaw committed
158
                                              force, quiet=quiet,
159
                                              legacy=legacy, optimize=optimize)
160
    return success
161

162

163
def main():
164
    """Script main program."""
165 166 167 168
    import argparse

    parser = argparse.ArgumentParser(
        description='Utilities to support installing Python libraries.')
169 170 171
    parser.add_argument('-l', action='store_const', const=0,
                        default=10, dest='maxlevels',
                        help="don't recurse into subdirectories")
172 173 174
    parser.add_argument('-f', action='store_true', dest='force',
                        help='force rebuild even if timestamps are up to date')
    parser.add_argument('-q', action='store_true', dest='quiet',
175
                        help='output only error messages')
176
    parser.add_argument('-b', action='store_true', dest='legacy',
177
                        help='use legacy (pre-PEP3147) compiled file locations')
178
    parser.add_argument('-d', metavar='DESTDIR',  dest='ddir', default=None,
179
                        help=('directory to prepend to file paths for use in '
180
                              'compile-time tracebacks and in runtime '
181 182
                              'tracebacks in cases where the source file is '
                              'unavailable'))
183
    parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
184 185 186
                        help=('skip files matching the regular expression; '
                              'the regexp is searched for in the full path '
                              'of each file considered for compilation'))
187
    parser.add_argument('-i', metavar='FILE', dest='flist',
188
                        help=('add all the files and directories listed in '
189 190
                              'FILE to the list considered for compilation; '
                              'if "-", names are read from stdin'))
191 192 193 194
    parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
                        help=('zero or more file and directory names '
                              'to compile; if no arguments given, defaults '
                              'to the equivalent of -l sys.path'))
195 196
    args = parser.parse_args()

197 198 199 200 201
    compile_dests = args.compile_dest

    if (args.ddir and (len(compile_dests) != 1
            or not os.path.isdir(compile_dests[0]))):
        parser.exit('-d destdir requires exactly one directory argument')
202 203 204 205 206 207
    if args.rx:
        import re
        args.rx = re.compile(args.rx)

    # if flist is provided then load it
    if args.flist:
208 209 210 211
        try:
            with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
                for line in f:
                    compile_dests.append(line.strip())
212
        except OSError:
213 214 215 216
            print("Error reading file list {}".format(args.flist))
            return False

    success = True
217
    try:
218 219
        if compile_dests:
            for dest in compile_dests:
220 221 222 223 224
                if os.path.isfile(dest):
                    if not compile_file(dest, args.ddir, args.force, args.rx,
                                        args.quiet, args.legacy):
                        success = False
                else:
225 226 227
                    if not compile_dir(dest, args.maxlevels, args.ddir,
                                       args.force, args.rx, args.quiet,
                                       args.legacy):
228 229
                        success = False
            return success
230
        else:
231
            return compile_path(legacy=args.legacy)
232
    except KeyboardInterrupt:
233
        print("\n[interrupted]")
234 235
        return False
    return True
236

237 238

if __name__ == '__main__':
239
    exit_status = int(not main())
240
    sys.exit(exit_status)