Linux+樹莓派3開發總結——cx_Freeze打包Python3程式(工程檔案)
Python是一個指令碼語言,被直譯器解釋執行。它的釋出方式:
-
.py檔案:對於開源專案或者原始碼沒那麼重要的,直接提供原始碼,需要使用者自行安裝Python並且安裝依賴的各種庫。(Python官方的各種安裝包就是這樣做的)
-
.pyc檔案:有些公司或個人因為機密或者各種原因,不願意原始碼被執行者看到,可以使用pyc檔案釋出,pyc檔案是Python直譯器可以識別的二進位制碼,故釋出後也是跨平臺的,需要使用者安裝相應版本的Python和依賴庫。
-
可執行檔案:對於非碼農使用者或者一些小白使用者,你讓他裝個Python同時還要折騰一堆依賴庫,那簡直是個災難。對於此類使用者,最簡單的方式就是提供一個可執行檔案,只需要把用法告訴Ta即可。比較麻煩的是需要針對不同平臺需要打包不同的可執行檔案(Windows,Linux,Mac,...)。
本文主要就是介紹最後一種方式,.py和.pyc都比較簡單,Python本身就可以搞定。將Python指令碼打包成可執行檔案有多種方式,本文重點介紹cx_Freeze,其它僅作比較和參考。
Freezing Your Code
各種打包Python程式對比 點選開啟連結
Solution | Windows | Linux | OS X | Python 3 | License | One-file mode | Zipfile import | Eggs | pkg_resources support |
---|---|---|---|---|---|---|---|---|---|
bbFreeze | yes | yes | yes | no | MIT | no | yes | yes | yes |
py2exe | yes | no | no | yes | MIT | yes | yes | no | no |
pyInstaller | yes | yes | yes | no | GPL | yes | no | yes | no |
cx_Freeze | yes | yes | yes | yes | PSF | no | yes | yes | no |
py2app | no | no | yes | yes | MIT | no | yes | yes | yes |
我要打包的環境是Linux+Python3,故根據情況我們採用cx_Freeze打包程式
Python3程式打包步驟:
1、下載cx_Freeze-4.3.4.tar.gz原始碼
2、解壓原始碼到某個目錄
3、開啟終端到解壓目錄
4、執行python3 setup.py build
這編譯會出錯
build/temp.linux-x86_64-2.7/source/bases/Console.o:在函式‘GetImporterHelper’中:
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Common.c:211:對‘PyObject_CallMethod’未定義的引用
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Common.c:215:對‘PyErr_Clear’未定義的引用
build/temp.linux-x86_64-2.7/source/bases/Console.o:在函式‘GetDirName’中:
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Common.c:66:對‘PyString_FromStringAndSize’未定義的引用
build/temp.linux-x86_64-2.7/source/bases/Console.o:在函式‘FatalError’中:
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Console.c:24:對‘PyErr_Print’未定義的引用
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Console.c:25:對‘Py_FatalError’未定義的引用
build/temp.linux-x86_64-2.7/source/bases/Console.o:在函式‘SetExecutableName’中:
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Common.c:93:對‘PyString_FromString’未定義的引用
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Common.c:115:對‘PyString_FromStringAndSize’未定義的引用
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Common.c:136:對‘PyString_FromString’未定義的引用
build/temp.linux-x86_64-2.7/source/bases/Console.o:在函式‘FatalError’中:
/home/bill/Downloads/cx_Freeze-4.3.3/source/bases/Console.c:24:對‘PyErr_Print’未定義的引用查了一下 網上有修改setup.py 將其中的if not vars.get("Py_ENABLE_SHARED", 0):修改成if True:
就可以了
5、執行安裝命令sudo python3 setup.py install
6、此時再次開啟一個終端,輸入命令:cxfreeze --help有內容說明安裝
7、打包命令輸入:
查詢版本:
cxfreeze --version
打包檔案(包含執行需要的檔案):cxfreeze ~/Desktop/Nt2000_Python1/Nt_Main.py --target-dir ~/Desktop/setup
格式為:cxfreeze 檔案絕對路徑 --target-dir 打包到目標可執行資料夾路徑
打包成一個可執行檔案命令:
cxfreeze D:/hello.py --target-dir D:/123 --no-copy-deps