Back to index

python3.2  3.2.2
Functions | Variables
compileall Namespace Reference

Functions

def compile_dir
def compile_file
def compile_path
def main

Variables

list __all__ = ["compile_dir","compile_file","compile_path"]
tuple exit_status = int(not main())

Detailed Description

Module/script to byte-compile all .py files to .pyc (or .pyo) files.

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.

Function Documentation

def compileall.compile_dir (   dir,
  maxlevels = 10,
  ddir = None,
  force = False,
  rx = None,
  quiet = False,
  legacy = False,
  optimize = -1 
)
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:      the directory that will be prepended to the path to the
           file as it is compiled into each byte-code file.
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
optimize:  optimization level or -1 for level of the interpreter

Definition at line 23 of file compileall.py.

00023 
00024                 quiet=False, legacy=False, optimize=-1):
00025     """Byte-compile all modules in the given directory tree.
00026 
00027     Arguments (only dir is required):
00028 
00029     dir:       the directory to byte-compile
00030     maxlevels: maximum recursion level (default 10)
00031     ddir:      the directory that will be prepended to the path to the
00032                file as it is compiled into each byte-code file.
00033     force:     if True, force compilation, even if timestamps are up-to-date
00034     quiet:     if True, be quiet during compilation
00035     legacy:    if True, produce legacy pyc paths instead of PEP 3147 paths
00036     optimize:  optimization level or -1 for level of the interpreter
00037     """
00038     if not quiet:
00039         print('Listing {!r}...'.format(dir))
00040     try:
00041         names = os.listdir(dir)
00042     except os.error:
00043         print("Can't list {!r}".format(dir))
00044         names = []
00045     names.sort()
00046     success = 1
00047     for name in names:
00048         if name == '__pycache__':
00049             continue
00050         fullname = os.path.join(dir, name)
00051         if ddir is not None:
00052             dfile = os.path.join(ddir, name)
00053         else:
00054             dfile = None
00055         if not os.path.isdir(fullname):
00056             if not compile_file(fullname, ddir, force, rx, quiet,
00057                                 legacy, optimize):
00058                 success = 0
00059         elif (maxlevels > 0 and name != os.curdir and name != os.pardir and
00060               os.path.isdir(fullname) and not os.path.islink(fullname)):
00061             if not compile_dir(fullname, maxlevels - 1, dfile, force, rx,
00062                                quiet, legacy, optimize):
00063                 success = 0
00064     return success

Here is the call graph for this function:

Here is the caller graph for this function:

def compileall.compile_file (   fullname,
  ddir = None,
  force = False,
  rx = None,
  quiet = False,
  legacy = False,
  optimize = -1 
)
Byte-compile one file.

Arguments (only fullname is required):

fullname:  the file to byte-compile
ddir:      if given, the directory name compiled in to the
           byte-code file.
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
optimize:  optimization level or -1 for level of the interpreter

Definition at line 66 of file compileall.py.

00066 
00067                  legacy=False, optimize=-1):
00068     """Byte-compile one file.
00069 
00070     Arguments (only fullname is required):
00071 
00072     fullname:  the file to byte-compile
00073     ddir:      if given, the directory name compiled in to the
00074                byte-code file.
00075     force:     if True, force compilation, even if timestamps are up-to-date
00076     quiet:     if True, be quiet during compilation
00077     legacy:    if True, produce legacy pyc paths instead of PEP 3147 paths
00078     optimize:  optimization level or -1 for level of the interpreter
00079     """
00080     success = 1
00081     name = os.path.basename(fullname)
00082     if ddir is not None:
00083         dfile = os.path.join(ddir, name)
00084     else:
00085         dfile = None
00086     if rx is not None:
00087         mo = rx.search(fullname)
00088         if mo:
00089             return success
00090     if os.path.isfile(fullname):
00091         if legacy:
00092             cfile = fullname + ('c' if __debug__ else 'o')
00093         else:
00094             if optimize >= 0:
00095                 cfile = imp.cache_from_source(fullname,
00096                                               debug_override=not optimize)
00097             else:
00098                 cfile = imp.cache_from_source(fullname)
00099             cache_dir = os.path.dirname(cfile)
00100         head, tail = name[:-3], name[-3:]
00101         if tail == '.py':
00102             if not force:
00103                 try:
00104                     mtime = int(os.stat(fullname).st_mtime)
00105                     expect = struct.pack('<4sl', imp.get_magic(), mtime)
00106                     with open(cfile, 'rb') as chandle:
00107                         actual = chandle.read(8)
00108                     if expect == actual:
00109                         return success
00110                 except IOError:
00111                     pass
00112             if not quiet:
00113                 print('Compiling {!r}...'.format(fullname))
00114             try:
00115                 ok = py_compile.compile(fullname, cfile, dfile, True,
00116                                         optimize=optimize)
00117             except py_compile.PyCompileError as err:
00118                 if quiet:
00119                     print('*** Error compiling {!r}...'.format(fullname))
00120                 else:
00121                     print('*** ', end='')
00122                 # escape non-printable characters in msg
00123                 msg = err.msg.encode(sys.stdout.encoding,
00124                                      errors='backslashreplace')
00125                 msg = msg.decode(sys.stdout.encoding)
00126                 print(msg)
00127                 success = 0
00128             except (SyntaxError, UnicodeError, IOError) as e:
00129                 if quiet:
00130                     print('*** Error compiling {!r}...'.format(fullname))
00131                 else:
00132                     print('*** ', end='')
00133                 print(e.__class__.__name__ + ':', e)
00134                 success = 0
00135             else:
00136                 if ok == 0:
00137                     success = 0
00138     return success

Here is the call graph for this function:

Here is the caller graph for this function:

def compileall.compile_path (   skip_curdir = 1,
  maxlevels = 0,
  force = False,
  quiet = False,
  legacy = False,
  optimize = -1 
)
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)
force: as for compile_dir() (default False)
quiet: as for compile_dir() (default False)
legacy: as for compile_dir() (default False)
optimize: as for compile_dir() (default -1)

Definition at line 140 of file compileall.py.

00140 
00141                  legacy=False, optimize=-1):
00142     """Byte-compile all module on sys.path.
00143 
00144     Arguments (all optional):
00145 
00146     skip_curdir: if true, skip current directory (default true)
00147     maxlevels:   max recursion level (default 0)
00148     force: as for compile_dir() (default False)
00149     quiet: as for compile_dir() (default False)
00150     legacy: as for compile_dir() (default False)
00151     optimize: as for compile_dir() (default -1)
00152     """
00153     success = 1
00154     for dir in sys.path:
00155         if (not dir or dir == os.curdir) and skip_curdir:
00156             print('Skipping current directory')
00157         else:
00158             success = success and compile_dir(dir, maxlevels, None,
00159                                               force, quiet=quiet,
00160                                               legacy=legacy, optimize=optimize)
00161     return success
00162 

Here is the call graph for this function:

Here is the caller graph for this function:

def compileall.main ( void  )
Script main program.

Definition at line 163 of file compileall.py.

00163 
00164 def main():
00165     """Script main program."""
00166     import argparse
00167 
00168     parser = argparse.ArgumentParser(
00169         description='Utilities to support installing Python libraries.')
00170     parser.add_argument('-l', action='store_const', const=0,
00171                         default=10, dest='maxlevels',
00172                         help="don't recurse into subdirectories")
00173     parser.add_argument('-f', action='store_true', dest='force',
00174                         help='force rebuild even if timestamps are up to date')
00175     parser.add_argument('-q', action='store_true', dest='quiet',
00176                         help='output only error messages')
00177     parser.add_argument('-b', action='store_true', dest='legacy',
00178                         help='use legacy (pre-PEP3147) compiled file locations')
00179     parser.add_argument('-d', metavar='DESTDIR',  dest='ddir', default=None,
00180                         help=('directory to prepend to file paths for use in '
00181                               'compile time tracebacks and in runtime '
00182                               'tracebacks in cases where the source file is '
00183                               'unavailable'))
00184     parser.add_argument('-x', metavar='REGEXP', dest='rx', default=None,
00185                         help=('skip files matching the regular expression. '
00186                               'The regexp is searched for in the full path '
00187                               'to each file considered for compilation.'))
00188     parser.add_argument('-i', metavar='FILE', dest='flist',
00189                         help=('add all the files and directories listed in '
00190                               'FILE to the list considered for compilation. '
00191                               'If "-", names are read from stdin.'))
00192     parser.add_argument('compile_dest', metavar='FILE|DIR', nargs='*',
00193                         help=('zero or more file and directory names '
00194                               'to compile; if no arguments given, defaults '
00195                               'to the equivalent of -l sys.path'))
00196     args = parser.parse_args()
00197 
00198     compile_dests = args.compile_dest
00199 
00200     if (args.ddir and (len(compile_dests) != 1
00201             or not os.path.isdir(compile_dests[0]))):
00202         parser.exit('-d destdir requires exactly one directory argument')
00203     if args.rx:
00204         import re
00205         args.rx = re.compile(args.rx)
00206 
00207     # if flist is provided then load it
00208     if args.flist:
00209         try:
00210             with (sys.stdin if args.flist=='-' else open(args.flist)) as f:
00211                 for line in f:
00212                     compile_dests.append(line.strip())
00213         except EnvironmentError:
00214             print("Error reading file list {}".format(args.flist))
00215             return False
00216 
00217     success = True
00218     try:
00219         if compile_dests:
00220             for dest in compile_dests:
00221                 if os.path.isfile(dest):
00222                     if not compile_file(dest, args.ddir, args.force, args.rx,
00223                                         args.quiet, args.legacy):
00224                         success = False
00225                 else:
00226                     if not compile_dir(dest, args.maxlevels, args.ddir,
00227                                        args.force, args.rx, args.quiet,
00228                                        args.legacy):
00229                         success = False
00230             return success
00231         else:
00232             return compile_path(legacy=args.legacy)
00233     except KeyboardInterrupt:
00234         print("\n[interrupted]")
00235         return False
00236     return True
00237 

Here is the call graph for this function:


Variable Documentation

list compileall.__all__ = ["compile_dir","compile_file","compile_path"]

Definition at line 20 of file compileall.py.

Definition at line 239 of file compileall.py.