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 as the name of the source file in error messagesinstead offile. 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

A 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.

New 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.

py_compile.main(args=None)

Compile several source files. The files named inargs (or on the commandline, ifargs isNone) are compiled and the resulting byte-code iscached in the normal manner. This function does not search a directorystructure to locate source files; it only compiles files named explicitly.If'-' is the only parameter in args, the list of files is taken fromstandard input.

Changed in version 3.2:Added support for'-'.

When this module is run as a script, themain() is used to compile all thefiles named on the command line. The exit status is nonzero if one of the filescould not be compiled.

See also

Modulecompileall

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