python 如何打包成exe文件
-
步骤 1:安装 PyInstaller
在终端或命令提示符中运行:pip install pyinstaller
-
步骤 2:基本打包命令
假设你的Python脚本名为 main.py,在终端中执行:pyinstaller --onefile main.py
–onefile 表示生成单个exe文件(默认生成多个文件)。
生成的exe文件位于 dist 目录下。 -
步骤 3:处理依赖项(可选)
如果程序依赖外部文件(如图片、配置文件等):pyinstaller --onefile --add-data "source_path;dest_path" main.py source_path:文件或文件夹路径(Windows用分号;,Linux/macOS用冒号:)。 dest_path:打包后文件在程序中的相对路径(如 data)。
-
步骤 4:隐藏控制台窗口(GUI程序)
如果是图形界面程序(如Tkinter、PyQt),添加 --noconsole: pyinstaller --onefile --noconsole main.py 示例完整命令 假设程序需要图标 app.ico 和数据文件 config.json: pyinstaller --onefile --icon=app.ico --add-data "config.json;." main.py