py_compile — Compile Python source files

Source code:Lib/py_compile.py


Thepy_compile module provides a function to generate a byte-code filefrom a source file, and another function used when the module source file isinvoked as a script.

Though not often needed, this function can be useful when installing modules forshared use, especially if some of the users may not have permission to write thebyte-code cache files in the directory containing the source code.

exceptionpy_compile.PyCompileError

Exception raised when an error occurs while attempting to compile the file.

py_compile.compile(file,cfile=None,dfile=None,doraise=False,optimize=-1,invalidation_mode=PycInvalidationMode.TIMESTAMP,quiet=0)

Compile a source file to byte-code and write out the byte-code cache file.The source code is loaded from the file namedfile. The byte-code iswritten tocfile, which defaults to thePEP 3147/PEP 488 path, endingin.pyc.For example, iffile is/foo/bar/baz.pycfile will default to/foo/bar/__pycache__/baz.cpython-32.pyc for Python 3.2. Ifdfile isspecified, it is used instead offile as the name of the source file fromwhich source lines are obtained for display in exception tracebacks.Ifdoraise is true, aPyCompileError is raisedwhen an error is encountered while compilingfile. Ifdoraise is false(the default), an error string is written tosys.stderr, but no exceptionis raised. This function returns the path to byte-compiled file, i.e.whatevercfile value was used.

Thedoraise andquiet arguments determine how errors are handled whilecompiling file. Ifquiet is 0 or 1, anddoraise is false, the defaultbehaviour is enabled: an error string is written tosys.stderr, and thefunction returnsNone instead of a path. Ifdoraise is true,aPyCompileError is raised instead. However ifquiet is 2,no message is written, anddoraise has no effect.

If the path thatcfile becomes (either explicitly specified or computed)is a symlink or non-regular file,FileExistsError will be raised.This is to act as a warning that import will turn those paths into regularfiles if it is allowed to write byte-compiled files to those paths. This isa side-effect of import using file renaming to place the final byte-compiledfile into place to prevent concurrent file writing issues.

optimize controls the optimization level and is passed to the built-incompile() function. The default of-1 selects the optimizationlevel of the current interpreter.

invalidation_mode should be a member of thePycInvalidationModeenum and controls how the generated bytecode cache is invalidated atruntime. The default isPycInvalidationMode.CHECKED_HASH iftheSOURCE_DATE_EPOCH environment variable is set, otherwisethe default isPycInvalidationMode.TIMESTAMP.

Changed in version 3.2:Changed default value ofcfile to bePEP 3147-compliant. Previousdefault wasfile +'c' ('o' if optimization was enabled).Also added theoptimize parameter.

Changed in version 3.4:Changed code to useimportlib for the byte-code cache file writing.This means file creation/writing semantics now match whatimportlibdoes, e.g. permissions, write-and-move semantics, etc. Also added thecaveat thatFileExistsError is raised ifcfile is a symlink ornon-regular file.

Changed in version 3.7:Theinvalidation_mode parameter was added as specified inPEP 552.If theSOURCE_DATE_EPOCH environment variable is set,invalidation_mode will be forced toPycInvalidationMode.CHECKED_HASH.

Changed in version 3.7.2:TheSOURCE_DATE_EPOCH environment variable no longeroverrides the value of theinvalidation_mode argument, and determinesits default value instead.

Changed in version 3.8:Thequiet parameter was added.

classpy_compile.PycInvalidationMode

An enumeration of possible methods the interpreter can use to determinewhether a bytecode file is up to date with a source file. The.pyc fileindicates the desired invalidation mode in its header. SeeCached bytecode invalidation for more information on how Python invalidates.pyc files at runtime.

Added in version 3.7.

TIMESTAMP

The.pyc file includes the timestamp and size of the source file,which Python will compare against the metadata of the source file atruntime to determine if the.pyc file needs to be regenerated.

CHECKED_HASH

The.pyc file includes a hash of the source file content, which Pythonwill compare against the source at runtime to determine if the.pycfile needs to be regenerated.

UNCHECKED_HASH

LikeCHECKED_HASH, the.pyc file includes a hash of the sourcefile content. However, Python will at runtime assume the.pyc file isup to date and not validate the.pyc against the source file at all.

This option is useful when the.pycs are kept up to date by somesystem external to Python like a build system.

Command-Line Interface

This module can be invoked as a script to compile several sourcefiles. The files named infilenames are compiled and the resultingbytecode is cached in the normal manner. This program does not searcha directory structure to locate source files; it only compiles filesnamed explicitly. The exit status is nonzero if one of the files couldnot be compiled.

<file>...<fileN>
-

Positional arguments are files to compile. If- is the onlyparameter, the list of files is taken from standard input.

-q,--quiet

Suppress errors output.

Changed in version 3.2:Added support for-.

Changed in version 3.10:Added support for-q.

See also

Modulecompileall

Utilities to compile all Python source files in a directory tree.