บางครั้งเราอยากสร้างโปรแกรม Python แล้วแจกให้เพื่อนใช้ โดยไม่ต้องให้ติดตั้ง Python และโมดูลต่างๆ เอง CX_Freeze ช่วยแก้ปัญหานี้ได้
ขั้นตอนการใช้งาน
1. ติดตั้ง CX_Freeze
pip install cx_Freeze
2. เตรียมโปรแกรม Python ที่ต้องการแปลง
ตัวอย่าง: โปรแกรมค้นหาบน python.com (บันทึกเป็น pythonCX_Freeze.py)
import urllib.request
import urllib.parse
import re
import time
my_url = 'https://www.python.com/'
my_values = {'s': 'basics', 'submit': 'search'}
my_data = urllib.parse.urlencode(my_values)
my_data = my_data.encode('utf-8')
my_req = urllib.request.Request(my_url, my_data)
my_resp = urllib.request.urlopen(my_req)
my_respData = my_resp.read()
my_paragraphs = re.findall(r'(.*?)
', str(my_respData))
for p in my_paragraphs:
print(p)
time.sleep(20) # หน่วง 20 วินาที เพื่อดูผลลัพธ์ก่อนปิด
3. สร้างไฟล์ setup.py
from cx_Freeze import setup, Executable
setup(
name="pythonCX_Freeze",
version="0.1",
description="",
executables=[Executable("pythonCX_Freeze.py")]
)
คำอธิบาย:
name: ชื่อโปรแกรมversion: หมายเลขเวอร์ชันdescription: คำอธิบาย (ว่างได้)executables: ลิสต์ Executable ไฟล์ .py ที่ต้องการ build
4. Build Executable
เปิด Command Prompt ไปที่โฟลเดอร์ที่มี setup.py และรัน:
python setup.py build
จะได้โฟลเดอร์ build ภายในมีโฟลเดอร์ย่อย (เช่น exe.win32-3.x) ซึ่งภายในมีไฟล์ .exe ที่รันได้โดยไม่ต้องมี Python ติดตั้ง
ผลลัพธ์

ข้อควรระวัง: หากโปรแกรมใช้ไฟล์ภายนอก (รูปภาพ, config, dll) ต้องเพิ่มใน include_files ใน setup.py ด้วย