cx_Freeze đóng gói script Python thành file thực thi độc lập (không cần cài Python trên máy đích).
Cài đặt
pip install cx_Freeze
Script mẫu: pythonCX_Freeze.py
import urllib.request, urllib.parse, re, time
url = 'https://www.python.com/'
values = {'s': 'basics', 'submit': 'search'}
data = urllib.parse.urlencode(values).encode('utf-8')
req = urllib.request.Request(url, data)
resp = urllib.request.urlopen(req)
respData = resp.read()
paragraphs = re.findall(r'(.*?)
', str(respData))
for p in paragraphs:
print(p)
time.sleep(20) # giữ cửa sổ mở 20s
File setup.py
from cx_Freeze import setup, Executable
setup(
name="pythonCX_Freeze",
version="0.1",
description="Demo cx_Freeze",
executables=[Executable("pythonCX_Freeze.py")]
)
Build
python setup.py build
Kết quả: thư mục build/exe.win32-x.x/ chứa file .exe và các thư viện cần thiết.
Lưu ý
- Cần include các module ẩn (hidden imports) nếu cx_Freeze không tự phát hiện.
- Dùng
include_filescho tài nguyên (ảnh, config, data). - Tùy chọn
base="Win32GUI"cho app GUI (không hiện console). - Thay thế:
PyInstaller(phổ biến hơn, dễ dùng hơn).