一、Linux環境打包python工程
将程式傳遞到生産環境(甲方),不想要環境維護者或甲方看到源代碼,是以需要将源代碼打包成可執行檔案
https://pyinstaller.readthedocs.io/en/stable/requirements.html
一)安裝打包環境(PyInstaller)
1、安裝依賴包
yum install -y python-setuptools python-dev build-essential
2、下載下傳并安裝pyinstaller
在網址下載下傳pyisntaller的包,位址:https://github.com/pyinstaller/pyinstaller/releases ,下載下傳對應的tar包
cd ${BASE_DIR}
#下載下傳所需的release版本
tar -xvf pyinstaller-4.10.tar.gz
cd pyinstaller-4.10
pip3 install wheel
python3 setup.py install
如果中間沒有報錯的話,pyinstaller就安裝完成了
驗證pyinstaller
pyinstaller --version
4.10
3、打包python項目源碼
PyInstaller 工具的指令文法如下:
pyinstaller 選項 Python 源檔案(程式主檔案)
舉例
## 示例代碼
]# cat main.py
print("hello,world!")
pyinstaller -F main.py
編譯完成後,會将可執行檔案儲存到dist目錄下
]# tree -L 1 dist
dist
└── main
執行可執行檔案
]# ./dist/main
hello,world!
4、打包複雜環境,需修改配置檔案然後重新編譯
因為" pyinstaller -F 程式主檔案.py ”這個打包的方法它隻會打包目前目錄下的所有py檔案,而不會打包config和database兩個檔案夾,是以此時的可執行檔案打包的并不完整,此時該怎麼做
這種情況需要修改程式main.spec
# -*- mode: python ; coding: utf-8 -*-
block_cipher = None
a = Analysis(['main.py'],
pathex=['/app/test'],
binaries=[],
datas=[],
hiddenimports=[],
hookspath=[],
runtime_hooks=[],
excludes=[],
win_no_prefer_redirects=False,
win_private_assemblies=False,
cipher=block_cipher,
noarchive=False)
dict_database = Tree('/app/test/database',prefix='database')
a.datas += dict_database
dict_config = Tree('/app/test/config',prefix='config')
a.datas += dict_config
pyz = PYZ(a.pure, a.zipped_data,
cipher=block_cipher)
exe = EXE(pyz,
a.scripts,
a.binaries,
a.zipfiles,
a.datas,
[],
name='main',
debug=False,
bootloader_ignore_signals=False,
strip=False,
upx=True,
runtime_tmpdir=None,
console=True )
重新編譯
pyinstaller mian.spec