|
| 1 | +# Routines to force "compilation" of all .py files in a directory |
| 2 | +# tree or on sys.path. By default recursion is pruned at a depth of |
| 3 | +# 10 and the current directory, if it occurs in sys.path, is skipped. |
| 4 | +# When called as a script, compiles argument directories, or sys.path |
| 5 | +# if no arguments. |
| 6 | +# After a similar module by Sjoerd Mullender. |
| 7 | + |
| 8 | +import os |
| 9 | +import sys |
| 10 | +import py_compile |
| 11 | + |
| 12 | +def compile_dir(dir, maxlevels = 10): |
| 13 | + print 'Listing', dir, '...' |
| 14 | + try: |
| 15 | + names = os.listdir(dir) |
| 16 | + except os.error: |
| 17 | + print "Can't list", dir |
| 18 | + names = [] |
| 19 | + names.sort() |
| 20 | + for name in names: |
| 21 | + fullname = os.path.join(dir, name) |
| 22 | + if os.path.isfile(fullname): |
| 23 | + head, tail = name[:-3], name[-3:] |
| 24 | + if tail == '.py': |
| 25 | + print 'Compiling', fullname, '...' |
| 26 | + try: |
| 27 | + py_compile.compile(fullname) |
| 28 | + except KeyboardInterrupt: |
| 29 | + del names[:] |
| 30 | + print '\n[interrupt]' |
| 31 | + break |
| 32 | + except: |
| 33 | + print 'Sorry:', sys.exc_type + ':', |
| 34 | + print sys.exc_value |
| 35 | + elif maxlevels > 0 and \ |
| 36 | + name != os.curdir and name != os.pardir and \ |
| 37 | + os.path.isdir(fullname) and \ |
| 38 | + not os.path.islink(fullname): |
| 39 | + compile_dir(fullname, maxlevels - 1) |
| 40 | + |
| 41 | +def compile_path(skip_curdir = 1): |
| 42 | + for dir in sys.path: |
| 43 | + if dir == os.curdir and skip_curdir: |
| 44 | + print 'Skipping current directory' |
| 45 | + else: |
| 46 | + compile_dir(dir, 0) |
| 47 | + |
| 48 | +def main(): |
| 49 | + import getopt |
| 50 | + try: |
| 51 | + opts, args = getopt.getopt(sys.argv[1:], 'l') |
| 52 | + except getopt.error, msg: |
| 53 | + print msg |
| 54 | + print "usage: compileall [-l] [directory ...]" |
| 55 | + print "-l: don't recurse down" |
| 56 | + print "if no arguments, -l sys.path is assumed" |
| 57 | + maxlevels = 10 |
| 58 | + for o, a in opts: |
| 59 | + if o == '-l': maxlevels = 0 |
| 60 | + if args: |
| 61 | + for dir in sys.argv[1:]: |
| 62 | + compile_dir(dir, maxlevels) |
| 63 | + else: |
| 64 | + compile_path() |
| 65 | + |
| 66 | +if __name__ == '__main__': |
| 67 | + main() |
0 commit comments