Python py_compile Module
Example
Compile a source file to bytecode (.pyc) without running it:
import py_compile, tempfile, os
# Create a temporary Python source file and compile it to bytecode
with tempfile.NamedTemporaryFile('w', suffix='.py', delete=False) as f:
f.write('x = 1\n')
src = f.name
py_compile.compile(src, doraise=True)
print('OK')
os.remove(src)
Try it Yourself »
Definition and Usage
The py_compile module compiles Python source files to bytecode.
Use it in build steps or tooling to pre-compile modules without importing or executing them.
Members
Member | Description |
---|---|
PyCompileError | Error raised when compilation fails (contains detailed context). |
compile() | Compile a source file to bytecode; supports custom destination and error handling. |
main() | Command-line entry point (used when running python -m py_compile ). |