Guido van Rossum | 5c97167 | 1996-07-22 15:23:25 +0000 | [diff] [blame] | 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 | if type(sys.exc_type) == type(''): |
| 34 | exc_type_name = sys.exc_type |
| 35 | else: exc_type_name = sys.exc_type.__name__ |
| 36 | print 'Sorry:', exc_type_name + ':', |
| 37 | print sys.exc_value |
| 38 | elif maxlevels > 0 and \ |
| 39 | name != os.curdir and name != os.pardir and \ |
| 40 | os.path.isdir(fullname) and \ |
| 41 | not os.path.islink(fullname): |
| 42 | compile_dir(fullname, maxlevels - 1) |
| 43 | |
| 44 | def compile_path(skip_curdir = 1): |
| 45 | for dir in sys.path: |
| 46 | if dir == os.curdir and skip_curdir: |
| 47 | print 'Skipping current directory' |
| 48 | else: |
| 49 | compile_dir(dir, 0) |
| 50 | |
| 51 | def main(): |
| 52 | import getopt |
| 53 | try: |
| 54 | opts, args = getopt.getopt(sys.argv[1:], 'l') |
| 55 | except getopt.error, msg: |
| 56 | print msg |
| 57 | print "usage: compileall [-l] [directory ...]" |
| 58 | print "-l: don't recurse down" |
| 59 | print "if no arguments, -l sys.path is assumed" |
| 60 | maxlevels = 10 |
| 61 | for o, a in opts: |
| 62 | if o == '-l': maxlevels = 0 |
| 63 | if args: |
| 64 | for dir in sys.argv[1:]: |
| 65 | compile_dir(dir, maxlevels) |
| 66 | else: |
| 67 | compile_path() |
| 68 | |
| 69 | if __name__ == '__main__': |
| 70 | main() |