Back to index

python3.2  3.2.2
Classes | Functions | Variables
py_compile Namespace Reference

Classes

class  PyCompileError

Functions

def wr_long
def compile
def main

Variables

tuple MAGIC = imp.get_magic()
list __all__ = ["compile", "main", "PyCompileError"]

Detailed Description

Routine to "compile" a .py file to a .pyc (or .pyo) file.

This module has intimate knowledge of the format of .pyc files.

Function Documentation

def py_compile.compile (   file,
  cfile = None,
  dfile = None,
  doraise = False,
  optimize = -1 
)
Byte-compile one Python source file to Python bytecode.

:param file: The source file name.
:param cfile: The target byte compiled file name.  When not given, this
    defaults to the PEP 3147 location.
:param dfile: Purported file name, i.e. the file name that shows up in
    error messages.  Defaults to the source file name.
:param doraise: Flag indicating whether or not an exception should be
    raised when a compile error is found.  If an exception occurs and this
    flag is set to False, a string indicating the nature of the exception
    will be printed, and the function will return to the caller. If an
    exception occurs and this flag is set to True, a PyCompileError
    exception will be raised.
:param optimize: The optimization level for the compiler.  Valid values
    are -1, 0, 1 and 2.  A value of -1 means to use the optimization
    level of the current interpreter, as given by -O command line options.

:return: Path to the resulting byte compiled file.

Note that it isn't necessary to byte-compile Python modules for
execution efficiency -- Python itself byte-compiles a module when
it is loaded, and if it can, writes out the bytecode to the
corresponding .pyc (or .pyo) file.

However, if a Python installation is shared between users, it is a
good idea to byte-compile all modules upon installation, since
other users may not be able to write in the source directories,
and thus they won't be able to write the .pyc/.pyo file, and then
they would be byte-compiling every module each time it is loaded.
This can slow down program start-up considerably.

See compileall.py for a script/module that uses this module to
byte-compile all installed files (or all files in selected
directories).

Definition at line 75 of file py_compile.py.

00075 
00076 def compile(file, cfile=None, dfile=None, doraise=False, optimize=-1):
00077     """Byte-compile one Python source file to Python bytecode.
00078 
00079     :param file: The source file name.
00080     :param cfile: The target byte compiled file name.  When not given, this
00081         defaults to the PEP 3147 location.
00082     :param dfile: Purported file name, i.e. the file name that shows up in
00083         error messages.  Defaults to the source file name.
00084     :param doraise: Flag indicating whether or not an exception should be
00085         raised when a compile error is found.  If an exception occurs and this
00086         flag is set to False, a string indicating the nature of the exception
00087         will be printed, and the function will return to the caller. If an
00088         exception occurs and this flag is set to True, a PyCompileError
00089         exception will be raised.
00090     :param optimize: The optimization level for the compiler.  Valid values
00091         are -1, 0, 1 and 2.  A value of -1 means to use the optimization
00092         level of the current interpreter, as given by -O command line options.
00093 
00094     :return: Path to the resulting byte compiled file.
00095 
00096     Note that it isn't necessary to byte-compile Python modules for
00097     execution efficiency -- Python itself byte-compiles a module when
00098     it is loaded, and if it can, writes out the bytecode to the
00099     corresponding .pyc (or .pyo) file.
00100 
00101     However, if a Python installation is shared between users, it is a
00102     good idea to byte-compile all modules upon installation, since
00103     other users may not be able to write in the source directories,
00104     and thus they won't be able to write the .pyc/.pyo file, and then
00105     they would be byte-compiling every module each time it is loaded.
00106     This can slow down program start-up considerably.
00107 
00108     See compileall.py for a script/module that uses this module to
00109     byte-compile all installed files (or all files in selected
00110     directories).
00111     """
00112     with tokenize.open(file) as f:
00113         try:
00114             timestamp = int(os.fstat(f.fileno()).st_mtime)
00115         except AttributeError:
00116             timestamp = int(os.stat(file).st_mtime)
00117         codestring = f.read()
00118     try:
00119         codeobject = builtins.compile(codestring, dfile or file, 'exec',
00120                                       optimize=optimize)
00121     except Exception as err:
00122         py_exc = PyCompileError(err.__class__, err, dfile or file)
00123         if doraise:
00124             raise py_exc
00125         else:
00126             sys.stderr.write(py_exc.msg + '\n')
00127             return
00128     if cfile is None:
00129         if optimize >= 0:
00130             cfile = imp.cache_from_source(file, debug_override=not optimize)
00131         else:
00132             cfile = imp.cache_from_source(file)
00133     try:
00134         os.makedirs(os.path.dirname(cfile))
00135     except OSError as error:
00136         if error.errno != errno.EEXIST:
00137             raise
00138     with open(cfile, 'wb') as fc:
00139         fc.write(b'\0\0\0\0')
00140         wr_long(fc, timestamp)
00141         marshal.dump(codeobject, fc)
00142         fc.flush()
00143         fc.seek(0, 0)
00144         fc.write(MAGIC)
00145     return cfile

Here is the call graph for this function:

def py_compile.main (   args = None)
Compile several source files.

The files named in 'args' (or on the command line, if 'args' is
not specified) are compiled and the resulting bytecode is cached
in the normal manner.  This function does not search a directory
structure to locate source files; it only compiles files named
explicitly.  If '-' is the only parameter in args, the list of
files is taken from standard input.

Definition at line 146 of file py_compile.py.

00146 
00147 def main(args=None):
00148     """Compile several source files.
00149 
00150     The files named in 'args' (or on the command line, if 'args' is
00151     not specified) are compiled and the resulting bytecode is cached
00152     in the normal manner.  This function does not search a directory
00153     structure to locate source files; it only compiles files named
00154     explicitly.  If '-' is the only parameter in args, the list of
00155     files is taken from standard input.
00156 
00157     """
00158     if args is None:
00159         args = sys.argv[1:]
00160     rv = 0
00161     if args == ['-']:
00162         while True:
00163             filename = sys.stdin.readline()
00164             if not filename:
00165                 break
00166             filename = filename.rstrip('\n')
00167             try:
00168                 compile(filename, doraise=True)
00169             except PyCompileError as error:
00170                 rv = 1
00171                 sys.stderr.write("%s\n" % error.msg)
00172             except IOError as error:
00173                 rv = 1
00174                 sys.stderr.write("%s\n" % error)
00175     else:
00176         for filename in args:
00177             try:
00178                 compile(filename, doraise=True)
00179             except PyCompileError as error:
00180                 # return value to indicate at least one failure
00181                 rv = 1
00182                 sys.stderr.write(error.msg)
00183     return rv

Here is the call graph for this function:

def py_compile.wr_long (   f,
  x 
)
Internal; write a 32-bit int to a file in little-endian order.

Definition at line 68 of file py_compile.py.

00068 
00069 def wr_long(f, x):
00070     """Internal; write a 32-bit int to a file in little-endian order."""
00071     f.write(bytes([x         & 0xff,
00072                    (x >> 8)  & 0xff,
00073                    (x >> 16) & 0xff,
00074                    (x >> 24) & 0xff]))

Here is the caller graph for this function:


Variable Documentation

list py_compile.__all__ = ["compile", "main", "PyCompileError"]

Definition at line 17 of file py_compile.py.

tuple py_compile.MAGIC = imp.get_magic()

Definition at line 15 of file py_compile.py.