Tất cả chương trình Python tự động compile source code thành compiled code (gọi là byte code) trước khi thực thi.
Khi import một module lần đầu, hoặc khi source file mới hoặc file đã cập nhật so với file compiled gần đây, file .pyc sẽ được tạo khi compile trong cùng thư mục với file .py (từ Python 3 - file .pyc nằm trong thư mục con __pycache__ thay vì cùng thư mục). Cơ chế này tiết kiệm thời gian vì Python bỏ qua bước compile khi chạy chương trình lần sau.
Không tạo file .pyc nếu chạy script với import (file khác). Ví dụ: script file1.py import file2.py.
Cách dễ nhất tạo file PYC là import nó. Giả sử module tên MainP.py:
>>> import MainP
>>>
Tuy nhiên, nếu muốn tạo file .pyc cho module không được import, dùng module py_compile và compileall.
Module py_compile có thể compile thủ công bất kỳ module nào. Dùng py_compile.compile tương tác:
>>> import py_compile
>>> py_compile.compile('test.py')
'__pycache__\\test.cpython-36.pyc'
>>>
Sau khi chạy, file .pyc tạo trong thư mục __pycache__ (Python 3) hoặc cùng vị trí file test.py.
Để compile nhiều file cùng lúc, dùng py_compile.main():
>>> py_compile.main(['test1.py', 'test2.py', 'test_sample1.py', 'test_sample2.py'])
0
Để compile tất cả file trong thư mục, dùng compileall.compile_dir():
>>> import compileall
>>> compileall.compile_dir('gmplot')
Listing 'gmplot'...
Listing 'gmplot\.git'...
...
Compiling 'gmplot\__init__.py'...
Compiling 'gmplot\color_dicts.py'...
Compiling 'gmplot\gmplot.py'...
Compiling 'gmplot\google_maps_templates.py'...
Compiling 'gmplot\setup.py'...
Listing 'gmplot\tests'...
True
File .pyc tạo trong 'folder_name\__pycache__'.
Để compile tất cả file trong thư mục hoặc nhiều thư mục, dùng compile function:
C:\Users\rajesh>python -m compileall
Skipping current directory
Listing 'C:\Python\Python361\python36.zip'...
Can't list 'C:\Python\Python361\python36.zip'
Listing 'C:\Python\Python361\DLLs'...
Listing 'C:\Python\Python361\lib'...
Listing 'C:\Python\Python361'...
Compiling 'C:\Python\Python361\BeautifulSoup_script1.py'...
Compiling 'C:\Python\Python361\EDA_python1.py'...
Compiling 'C:\Python\Python361\MainP.py'...
...
File .pyc tạo cho tất cả file trong thư mục __pycache__.