cx_freeze是用來將 Python 腳本封裝成可執行程序的工具,支持最新的Python3.2版本。生成的執行文件具有跨平台性,而且運行的系統無須安裝Python。目前類似功能的工具還有py2exe 和 PyInstaller,其中貌似py2exe知名度最高了,但是很久沒有更新了,至於打包質量不做評價,畢竟蘿卜青菜各有所愛;PyInstaller不太了解,據說工序很復雜;至於cx_freeze的強大功能及易用性,本人強烈推薦。
詳細安裝步驟如下:
1. 安裝cx_freeze(官方下載地址:http://cx-freeze.sourceforge.net)
2. 檢查cx_freeze安裝是否成功(Windows OS)
3. 准備一個簡單的hello.py小程序

import time
print ("Hello World!")
time.sleep(5)
4. 把Python的腳本封裝成可執行文件(兩種方法)
- 使用參數:
CMD> cxfreeze hello.py --target-dir dist

- 使用配置文件(個人推薦=>一次編寫,到處可用☺):
CMD> python setup.py build
setup.py配置程序:

1 #
2 # 文 件 名:setup.py
3 # 功能描述:cx_freeze封裝Python腳本的配置文件
4 #
5 # 作者:Renzo 日期:2012/01/01
6 #
7 # 版權:可以使用、傳播,但請保留出處;如需修改,請告知作者。
8 #
9
10 from cx_Freeze import setup, Executable
11
12
13 # 首先處理path,includes,excludes,packages等內部變量
14 base = "Win32GUI"
15 path = []
16 includes = []
17 excludes = ['_gtkagg', '_tkagg', 'bsddb', 'curses', 'email', 'pywin.debugger',
18 'pywin.debugger.dbgcon', 'pywin.dialogs', 'tcl', 'Tkconstants',
19 'Tkinter']
20 packages = []
21
22
23 # 這里可以編寫客戶化的封裝前處理代碼。例如:數據文件的處理
24
25
26
27 # 配置封裝的參數
28 GUI2Exe_Target_Main = Executable(
29 path = path,
30 base = base,
31
32 # 生成可執行文件的主文件
33 script = "simple.py",
34
35 # 生成可執行文件及一些依賴文件的目錄
36 targetDir = r"dist",
37 # 可執行文件的名稱
38 targetName = "simple.exe",
39 # 可執行文件的ico圖標
40 icon = "simple.ico",
41
42 includes = includes,
43 excludes = excludes,
44 packages = packages,
45
46 # 是否需要壓縮模塊的字節碼
47 compress = True,
48
49 # 是否拷貝依賴文件到目標目錄
50 copyDependentFiles = True,
51
52 # 是否附加腳本模塊到執行文件
53 appendScriptToExe = True,
54 # 是否添加腳本模塊到共享庫
55 appendScriptToLibrary = False,
56
57 # 設置快捷方式的路徑及名稱
58 shortcutDir = "",
59 shortcutName = ""
60 )
61
62
63 # 設置安裝時軟件包的描述信息
64 setup(
65 name = "Simple",
66 version = "0.1",
67 description = "My first python program",
68
69 author = "Renzo",
70 author_email = "liurenzhong@yeah.net",
71
72 url = "wwww.cnblogs.com/renzo",
73
74 # 生成的可執行文件
75 executables = [GUI2Exe_Target_Main]
76 )
77
78
79 # 這里可以編寫客戶化的封裝后處理代碼。例如:臨時數據的清除,數據包的發布等
80
81
82
83 # 到此,整個setup腳本已經完成。

6. 執行結果
恭喜你,可以把整個目標目錄打包發布了。