下面我将介绍如何使用这两个工具来将 Python 脚本编译成 .exe 文件。
使用 PyInstaller
-
安装 PyInstaller: 你可以使用 pip 来安装 PyInstaller:
pip install pyinstaller -
编译脚本: 使用 PyInstaller 来编译你的 Python 脚本:
pyinstaller --onefile your_script.py其中
your_script.py是你要编译的 Python 脚本的名称。--onefile参数表示将所有依赖项打包到一个单独的可执行文件中。 -
查找生成的 .exe 文件: 编译完成后,你可以在
dist文件夹中找到生成的.exe文件。
使用 cx_Freeze
-
安装 cx_Freeze: 你可以使用 pip 来安装 cx_Freeze:
pip install cx_Freeze -
创建 setup.py 文件: 创建一个
setup.py文件,其中包含你的脚本信息:from cx_Freeze import setup, Executablebase = None if sys.platform == "win32":base = "Win32GUI"options = {'build_exe': {'packages': ["os"],'include_files': ['data_files']} }executables = [Executable("your_script.py", base=base)]setup(name="YourAppName",version="0.1",description="Your app description",options=options,executables=executables )在这个例子中,
your_script.py是你要编译的 Python 脚本的名称。 -
编译脚本: 使用
setup.py文件来编译你的脚本:python setup.py build -
查找生成的 .exe 文件: 编译完成后,你可以在
build文件夹中找到生成的.exe文件。
注意事项
- 依赖项:确保你的脚本中的所有依赖项都已经正确安装,并且在编译时被包含进去。对于 PyInstaller,你可以使用
--hidden-import参数来指定需要包含的隐藏依赖项。 - 兼容性:生成的
.exe文件只能在与编译时相同的平台上运行。例如,如果你在一个 64 位的 Windows 系统上编译,生成的.exe文件只能在 64 位的 Windows 系统上运行。 - 签名和安全性:生成的
.exe文件可能会被一些防病毒软件标记为潜在威胁,因此在分发之前最好对其进行数字签名。
