当前位置: 代码网 > it编程>前端脚本>Python > 使用PyInstaller将Python脚本打包成exe的新手入门指南

使用PyInstaller将Python脚本打包成exe的新手入门指南

2026年03月29日 Python 我要评论
辛辛苦苦写好的 python 脚本,发给同事却要让他装环境?用 pyinstaller 打包成单个 exe 文件,双击就能运行,省心又专业。本文从零开始,手把手教你用 pyinstaller 打包 p

辛辛苦苦写好的 python 脚本,发给同事却要让他装环境?用 pyinstaller 打包成单个 exe 文件,双击就能运行,省心又专业。本文从零开始,手把手教你用 pyinstaller 打包 python 程序,解决新手常遇到的坑。

一、为什么需要 pyinstaller?

写了个自动化脚本,发给同事,他说“python 是啥?怎么运行?” 如果你不想让每个人都安装 python 和依赖包,pyinstaller 就是救星。

pyinstaller 的作用:把 python 脚本及其依赖打包成一个独立的可执行文件(windows 下是 .exe),用户无需 python 环境,双击即可运行。

支持平台:windows、macos、linux。

二、安装 pyinstaller

最简单的方式是用 pip 安装:pip install pyinstaller

如果下载慢,可以换国内源:pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pyinstaller

安装完成后,在命令行输入以下命令确认是否成功:pyinstaller --version

正常会显示版本号,如 6.7.0

三、快速上手:打包一个最简单的脚本

假设我们有一个名为 hello.py 的脚本,内容如下:

print("hello, pyinstaller!")
input("按回车键退出...")

进入脚本所在目录,打开命令行,执行:

pyinstaller hello.py

命令执行后,会生成两个目录:

  • build:临时文件目录(可忽略)
  • dist:打包好的可执行文件就在这里

在 dist/hello 目录下(windows 为 dist/hello)找到 hello.exe(或 hello),双击运行,就能看到输出结果。

注意:默认生成的是一个文件夹,里面包含 exe 和一堆依赖文件。如果想生成单个 exe 文件,加上 -f 参数:

pyinstaller -f hello.py

此时 dist 目录下只有一个 hello.exe,双击就能运行。

四、常用参数详解

-f, --onefile:打包成单个 exe 文件

-d, --onedir:打包成一个文件夹(默认)

-w, --windowed:不显示控制台窗口(适用于 gui 程序)

-i, --icon:指定 exe 的图标(如 -i icon.ico

--name:指定生成的 exe 文件名

--add-data:添加额外数据文件(如图片、配置文件)

--hidden-import:手动导入 pyinstaller 未能自动发现的模块

五、实战:打包带依赖和 gui 的程序

假设我们有一个简单的 gui 程序 gui_app.py,用 tkinter 做了一个小窗口,还依赖一个外部的 config.json 文件。

import tkinter as tk
import json

with open("config.json", "r", encoding="utf-8") as f:
    config = json.load(f)

root = tk.tk()
root.title(config.get("title", "my app"))
label = tk.label(root, text=config.get("text", "hello"))
label.pack()
root.mainloop()

config.json内容:

{
    "title": "我的应用",
    "text": "欢迎使用 pyinstaller"
}

1. 打包单个 exe,不显示控制台窗口

pyinstaller -f -w --add-data "config.json;." gui_app.py

解释

  • -f:单文件
  • -w:无控制台窗口
  • --add-data "config.json;.":将 config.json 文件添加到打包中,并放在 exe 同目录(; 是 windows 下的分隔符,linux/macos 用 :

2. 解决路径问题

程序里如果使用相对路径读取配置文件,打包后可能会找不到。推荐在代码中自动获取正确的路径:

import sys
import os

def resource_path(relative_path):
    """获取资源的绝对路径,适配 pyinstaller 打包"""
    try:
        base_path = sys._meipass  # pyinstaller 临时解压目录
    except attributeerror:
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

# 使用
config_path = resource_path("config.json")
with open(config_path, "r") as f:
    config = json.load(f)

然后在打包时,添加 --add-data 并告知 pyinstaller 将文件放到 _meipass 目录下。

pyinstaller -f -w --add-data "config.json;." gui_app.py

这样即使打包成单个 exe,程序也能正确读取到配置文件。

六、常见问题与解决方案

1. 打包后运行报错:modulenotfounderror: no module named 'xxx'

原因:pyinstaller 没有自动识别到某些依赖模块。

解决:使用 --hidden-import 手动指定。

pyinstaller -f --hidden-import=pandas --hidden-import=openpyxl my_script.py

2. 打包文件太大,怎么办?

使用 --exclude-module 排除不需要的模块(如 matplotlibnumpy 很占体积)。

如果用了虚拟环境,在干净的环境中打包,避免打包多余包。

3. 图标不生效

确保图标是 .ico 格式(windows 下),其他格式可能不识别。打包时:

pyinstaller -f -i myicon.ico my_script.py

4. 打包后双击闪退

闪退通常是因为程序报错后立即退出。可以在代码开头加 try...except 捕获错误并暂停:

try:
    # 你的代码
except exception as e:
    print("error:", e)
    input("按回车键退出...")

这样就能看到错误信息,方便排查。

七、进阶:使用 spec 文件自定义打包

当参数很多时,可以生成 .spec 配置文件,然后通过 pyinstaller xxx.spec 打包,方便修改和复用。

生成 spec 文件:

pyinstaller hello.py # 会生成 hello.spec

编辑 hello.spec,修改 a.datas 添加数据文件,修改 exe 设置图标等。然后执行:

pyinstaller hello.spec

八、总结

需求命令
基础打包pyinstaller script.py
打包成单个 exepyinstaller -f script.py
无控制台窗口pyinstaller -f -w script.py
指定图标pyinstaller -f -i icon.ico script.py
添加额外文件--add-data "file;."
隐藏导入--hidden-import=module

最佳实践

  • 在虚拟环境中打包,减少体积。
  • 使用 -f 生成单文件,便于分发。
  • 使用 resource_path 函数处理文件路径。
  • 遇到闪退时,先用控制台版本(不加 -w)调试。
  • 对于大型项目,用 spec 文件管理配置。

现在,你可以把自己的 python 脚本打包成 exe 发给任何人,再也不用担心环境问题了。快去试试吧!

到此这篇关于使用pyinstaller将python脚本打包成exe的新手入门指南的文章就介绍到这了,更多相关pyinstaller打包python脚本内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2026  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com