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

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.

"""
14 15

import os
16
import stat
17 18 19
import sys
import py_compile

20
def compile_dir(dir, maxlevels=10, ddir=None, force=0):
21 22 23 24 25 26 27 28
    """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)
    ddir:      if given, purported directory name (this is the
               directory name that will show up in error messages)
29
    force:     if 1, force compilation, even if timestamps are up-to-date
30

31 32 33
    """
    print 'Listing', dir, '...'
    try:
34
        names = os.listdir(dir)
35
    except os.error:
36 37
        print "Can't list", dir
        names = []
38
    names.sort()
39
    success = 1
40
    for name in names:
41 42 43 44 45 46 47 48
        fullname = os.path.join(dir, name)
        if ddir:
            dfile = os.path.join(ddir, name)
        else:
            dfile = None
        if os.path.isfile(fullname):
            head, tail = name[:-3], name[-3:]
            if tail == '.py':
49 50 51 52 53
                cfile = fullname + (__debug__ and 'c' or 'o')
                ftime = os.stat(fullname)[stat.ST_MTIME]
                try: ctime = os.stat(cfile)[stat.ST_MTIME]
                except os.error: ctime = 0
                if (ctime > ftime) and not force: continue
54 55 56 57 58 59 60 61 62 63 64
                print 'Compiling', fullname, '...'
                try:
                    py_compile.compile(fullname, None, dfile)
                except KeyboardInterrupt:
                    raise KeyboardInterrupt
                except:
                    if type(sys.exc_type) == type(''):
                        exc_type_name = sys.exc_type
                    else: exc_type_name = sys.exc_type.__name__
                    print 'Sorry:', exc_type_name + ':',
                    print sys.exc_value
65
                    success = 0
66 67 68 69
        elif maxlevels > 0 and \
             name != os.curdir and name != os.pardir and \
             os.path.isdir(fullname) and \
             not os.path.islink(fullname):
70
            compile_dir(fullname, maxlevels - 1, dfile, force)
71
    return success
72

73
def compile_path(skip_curdir=1, maxlevels=0, force=0):
74 75 76 77 78 79
    """Byte-compile all module on sys.path.

    Arguments (all optional):

    skip_curdir: if true, skip current directory (default true)
    maxlevels:   max recursion level (default 0)
80
    force: as for compile_dir() (default 0)
81 82

    """
83
    success = 1
84
    for dir in sys.path:
85 86 87
        if (not dir or dir == os.curdir) and skip_curdir:
            print 'Skipping current directory'
        else:
88 89
            success = success and compile_dir(dir, maxlevels, None, force)
    return success
90 91

def main():
92 93 94
    """Script main program."""
    import getopt
    try:
95
        opts, args = getopt.getopt(sys.argv[1:], 'lfd:')
96
    except getopt.error, msg:
97
        print msg
98
        print "usage: compileall [-l] [-f] [-d destdir] [directory ...]"
99
        print "-l: don't recurse down"
100
        print "-f: force rebuild even if timestamps are up-to-date"
101
        print "-d destdir: purported directory name for error messages"
102
        print "if no directory arguments, -l sys.path is assumed"
103
        sys.exit(2)
104 105
    maxlevels = 10
    ddir = None
106
    force = 0
107
    for o, a in opts:
108 109
        if o == '-l': maxlevels = 0
        if o == '-d': ddir = a
110
        if o == '-f': force = 1
111
    if ddir:
112 113 114
        if len(args) != 1:
            print "-d destdir require exactly one directory argument"
            sys.exit(2)
115
    success = 1
116
    try:
117 118
        if args:
            for dir in args:
119
                success = success and compile_dir(dir, maxlevels, ddir, force)
120
        else:
121
            success = compile_path()
122
    except KeyboardInterrupt:
123
        print "\n[interrupt]"
124 125
        success = 0
    return success
126 127

if __name__ == '__main__':
128
    sys.exit(not main())