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
7.. sectionauthor:: Fred L. Drake, Jr. <fdrake@acm.org>
8.. documentation based on module docstrings
9
10**Source code:** :source:`Lib/py_compile.py`
11
12.. index:: pair: file; byte-code
13
14--------------
15
16The :mod:`py_compile` module provides a function to generate a byte-code file
17from a source file, and another function used when the module source file is
18invoked as a script.
19
20Though not often needed, this function can be useful when installing modules for
21shared use, especially if some of the users may not have permission to write the
22byte-code cache files in the directory containing the source code.
23
24
25.. exception:: PyCompileError
26
27   Exception raised when an error occurs while attempting to compile the file.
28
29
30.. function:: compile(file, cfile=None, dfile=None, doraise=False, optimize=-1, invalidation_mode=PycInvalidationMode.TIMESTAMP, quiet=0)
31
32   Compile a source file to byte-code and write out the byte-code cache file.
33   The source code is loaded from the file named *file*.  The byte-code is
34   written to *cfile*, which defaults to the :pep:`3147`/:pep:`488` path, ending
35   in ``.pyc``.
36   For example, if *file* is ``/foo/bar/baz.py`` *cfile* will default to
37   ``/foo/bar/__pycache__/baz.cpython-32.pyc`` for Python 3.2.  If *dfile* is
38   specified, it is used instead of *file* as the name of the source file from
39   which source lines are obtained for display in exception tracebacks.
40   If *doraise* is true, a :exc:`PyCompileError` is raised
41   when an error is encountered while compiling *file*. If *doraise* is false
42   (the default), an error string is written to ``sys.stderr``, but no exception
43   is raised.  This function returns the path to byte-compiled file, i.e.
44   whatever *cfile* value was used.
45
46   The *doraise* and *quiet* arguments determine how errors are handled while
47   compiling file. If *quiet* is 0 or 1, and *doraise* is false, the default
48   behaviour is enabled: an error string is written to ``sys.stderr``, and the
49   function returns ``None`` instead of a path. If *doraise* is true,
50   a :exc:`PyCompileError` is raised instead. However if *quiet* is 2,
51   no message is written, and *doraise* has no effect.
52
53   If the path that *cfile* becomes (either explicitly specified or computed)
54   is a symlink or non-regular file, :exc:`FileExistsError` will be raised.
55   This is to act as a warning that import will turn those paths into regular
56   files if it is allowed to write byte-compiled files to those paths. This is
57   a side-effect of import using file renaming to place the final byte-compiled
58   file into place to prevent concurrent file writing issues.
59
60   *optimize* controls the optimization level and is passed to the built-in
61   :func:`compile` function.  The default of ``-1`` selects the optimization
62   level of the current interpreter.
63
64   *invalidation_mode* should be a member of the :class:`PycInvalidationMode`
65   enum and controls how the generated bytecode cache is invalidated at
66   runtime.  The default is :attr:`PycInvalidationMode.CHECKED_HASH` if
67   the :envvar:`SOURCE_DATE_EPOCH` environment variable is set, otherwise
68   the default is :attr:`PycInvalidationMode.TIMESTAMP`.
69
70   .. versionchanged:: 3.2
71      Changed default value of *cfile* to be :PEP:`3147`-compliant.  Previous
72      default was *file* + ``'c'`` (``'o'`` if optimization was enabled).
73      Also added the *optimize* parameter.
74
75   .. versionchanged:: 3.4
76      Changed code to use :mod:`importlib` for the byte-code cache file writing.
77      This means file creation/writing semantics now match what :mod:`importlib`
78      does, e.g. permissions, write-and-move semantics, etc. Also added the
79      caveat that :exc:`FileExistsError` is raised if *cfile* is a symlink or
80      non-regular file.
81
82   .. versionchanged:: 3.7
83      The *invalidation_mode* parameter was added as specified in :pep:`552`.
84      If the :envvar:`SOURCE_DATE_EPOCH` environment variable is set,
85      *invalidation_mode* will be forced to
86      :attr:`PycInvalidationMode.CHECKED_HASH`.
87
88   .. versionchanged:: 3.7.2
89      The :envvar:`SOURCE_DATE_EPOCH` environment variable no longer
90      overrides the value of the *invalidation_mode* argument, and determines
91      its default value instead.
92
93   .. versionchanged:: 3.8
94      The *quiet* parameter was added.
95
96
97.. class:: PycInvalidationMode
98
99   A enumeration of possible methods the interpreter can use to determine
100   whether a bytecode file is up to date with a source file. The ``.pyc`` file
101   indicates the desired invalidation mode in its header. See
102   :ref:`pyc-invalidation` for more information on how Python invalidates
103   ``.pyc`` files at runtime.
104
105   .. versionadded:: 3.7
106
107   .. attribute:: TIMESTAMP
108
109      The ``.pyc`` file includes the timestamp and size of the source file,
110      which Python will compare against the metadata of the source file at
111      runtime to determine if the ``.pyc`` file needs to be regenerated.
112
113   .. attribute:: CHECKED_HASH
114
115      The ``.pyc`` file includes a hash of the source file content, which Python
116      will compare against the source at runtime to determine if the ``.pyc``
117      file needs to be regenerated.
118
119   .. attribute:: UNCHECKED_HASH
120
121      Like :attr:`CHECKED_HASH`, the ``.pyc`` file includes a hash of the source
122      file content. However, Python will at runtime assume the ``.pyc`` file is
123      up to date and not validate the ``.pyc`` against the source file at all.
124
125      This option is useful when the ``.pycs`` are kept up to date by some
126      system external to Python like a build system.
127
128
129Command-Line Interface
130----------------------
131
132This module can be invoked as a script to compile several source
133files.  The files named in *filenames* are compiled and the resulting
134bytecode is cached in the normal manner.  This program does not search
135a directory structure to locate source files; it only compiles files
136named explicitly. The exit status is nonzero if one of the files could
137not be compiled.
138
139.. program:: python -m py_compile
140
141.. cmdoption:: <file> ... <fileN>
142               -
143
144   Positional arguments are files to compile.  If ``-`` is the only
145   parameter, the list of files is taken from standard input.
146
147.. cmdoption:: -q, --quiet
148
149   Suppress errors output.
150
151.. versionchanged:: 3.2
152   Added support for ``-``.
153
154.. versionchanged:: 3.10
155   Added support for :option:`-q`.
156
157
158.. seealso::
159
160   Module :mod:`compileall`
161      Utilities to compile all Python source files in a directory tree.
162