• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1:mod:`py_compile` --- Compile Python source files
2=================================================
3
4.. module:: py_compile
5   :synopsis: Generate byte-code files from Python source files.
6.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
7.. documentation based on module docstrings
8
9.. index:: pair: file; byte-code
10
11**Source code:** :source:`Lib/py_compile.py`
12
13--------------
14
15The :mod:`py_compile` module provides a function to generate a byte-code file
16from a source file, and another function used when the module source file is
17invoked as a script.
18
19Though not often needed, this function can be useful when installing modules for
20shared use, especially if some of the users may not have permission to write the
21byte-code cache files in the directory containing the source code.
22
23
24.. exception:: PyCompileError
25
26   Exception raised when an error occurs while attempting to compile the file.
27
28
29.. function:: compile(file[, cfile[, dfile[, doraise]]])
30
31   Compile a source file to byte-code and write out the byte-code cache  file.  The
32   source code is loaded from the file named *file*.  The  byte-code is written to
33   *cfile*, which defaults to *file* ``+`` ``'c'`` (``'o'`` if optimization is
34   enabled in the current interpreter).  If *dfile* is specified, it is used as the
35   name of the source file in error messages instead of *file*.  If *doraise* is
36   true, a :exc:`PyCompileError` is raised when an error is encountered while
37   compiling *file*. If *doraise* is false (the default), an error string is
38   written to ``sys.stderr``, but no exception is raised.
39
40
41.. function:: main([args])
42
43   Compile several source files.  The files named in *args* (or on the command
44   line, if *args* is not specified) are compiled and the resulting bytecode is
45   cached in the normal manner.  This function does not search a directory
46   structure to locate source files; it only compiles files named explicitly.
47   If ``'-'`` is the only parameter in args, the list of files is taken from
48   standard input.
49
50   .. versionchanged:: 2.7
51      Added support for ``'-'``.
52
53When this module is run as a script, the :func:`main` is used to compile all the
54files named on the command line.  The exit status is nonzero if one of the files
55could not be compiled.
56
57.. versionchanged:: 2.6
58   Added the nonzero exit status when module is run as a script.
59
60
61.. seealso::
62
63   Module :mod:`compileall`
64      Utilities to compile all Python source files in a directory tree.
65
66