手把手教你用PyInstaller打包Python程序

P粉084495128
发布: 2025-08-01 10:34:52
原创
421人浏览过
本文介绍使用PyInstaller打包Python项目的方法,以OCR截屏识别助手为例。先讲PyInstaller简介、环境准备和主要命令参数,再通过示例演示打包流程,包括处理多文件、UI资源、精简依赖和调整import路径,还提及Windows环境打包及效果。

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

手把手教你用pyinstaller打包python程序 - php中文网

序言

该项目的灵感来自一个现实的需求,现在有时候会遇到一些文档不能复制,但又不想装非常笨重、可能带广告、收费的文字处理软件,怎么办呢?

首先,要再次感谢7hinc童鞋——不好意思,又抢生意来了        

他的项目超好用的OCR截屏识别助手只用了3个Python文件和一个前端UI文件,就提供了比较完整的截图OCR识别功能。

但这个项目是基于Python的,并且依赖于非常强大的PaddleHub模型库和PaddleOCR项目——换言之,它依赖包很多。

如果我们想在另一台机器上运行,或者分享给不了解这方面技术的同事该怎么办呢?总不能再装一遍环境吧?        

由此,就引发了这个项目:如何将Python打包?当然,这里必须要提前说明——

立即进入豆包AI人工智官网入口”;

立即学习豆包AI人工智能在线问答入口”;

本文没有教如何打包Paddle各类库,包括PaddleOCR——为什么?

首先,用百度智能云开发者中心的免费API调用次数不香吗        

其次,本文会做个简单解释,告诉大家——实在太难了,此路真不通        

PyInstaller简介

没错,我们需要用到的打包工具就是PyInstaller,这是它的最新文档。看看它官网自己咋说的——

PyInstaller bundles a Python application and all its dependencies into a single package. The user can run the packaged app without installing a Python interpreter or any modules. PyInstaller supports Python > > 3.5 or newer, and correctly bundles the major Python packages such as numpy, PyQt, Django, wxPython, and others.

PyInstaller is tested against Windows, Mac OS X, and GNU/Linux. However, it is not a cross-compiler: to make a Windows app you run PyInstaller in Windows; to make a GNU/Linux app you run it in GNU/Linux, etc. > PyInstaller has been used successfully with AIX, Solaris, FreeBSD and OpenBSD but testing against them is not part of our continuous integration tests.

PyInstaller支持在Windows, Mac OS X, and GNU/Linux三个主流平台打包,Python版本要3.5以上,环境依赖库要安装正确。在不同的平台上使用 PyInstaller 工具的方法是一样的,它们支持的选项也是一样的。

同时,我们也会发现PyInstaller的打包依赖于它所在的操作系统,也就是说,我们在Linux平台打的包,就只适合在Linux环境中运行,Windows上启动不起来的。

环境准备

如何用PyInstaller呢?其实安装很简单,使用也很简单,但是——对环境要求比较高,如果在本机上没装好C++库,经常没有报错——缺这个DLL,缺那个DLL……

所以这里建议大家,如果要在本地的Windows系统上打包,最好不要偷懒,也不要心疼存储空间和那点时间,老老实实把Visual Studio 2019装起来吧——社区版就行了,它会自动把各种DLL依赖都准备好,通常在开发过程中就很少遇到类似报错了。

主要命令参数

具体用法可以参考PyInstaller的用户手册

生成结果¶

-D, --onedir 默认会生成一个文件夹
-F, --onefile 指定生成一个单独的可执行文件
--specpath DIR 指定spec文件的生成目录。默认使用当前目录来生成spec文件
-n NAME, --name NAME

指定项目(产生的 spec)名字。如果省略该选项,那么第一个脚本的主文件名将作为 spec 的名字

打包什么,从哪里找依赖¶

--add-data <SRC;DEST or SRC:DEST>  Additional non-binary files or folders to be added to the executable. The path separator is platform specific, os.pathsep (which is ; on Windows and : on most unix systems) is used. This option can be used multiple times.非二进制文件通过设置这个参数打包

--hidden-import MODULENAME, --hiddenimport MODULENAME  Name an import not visible in the code of the script(s). This option can be used multiple times.显式指定要import的依赖

从Demo开始

从学习的曲线来看,遇到新事物的时候还是建议循序渐进,比如找一个简单的Demo开始运行。所以这里提供了两个基础示例。

  • img2pdf.py可以将指定目录下的图片文件合成一个pdf文件
  • editor.py文件可以创建一个最简单的pyqt5窗口——这与我们的目标就很接近了

PyInstaller打包单文件

因为pyqt的GUI窗口在AI Studio上看不到,所以我们就先用img2pdf.py演示打包的流程和效果

In [ ]
# 首先,要确认python代码正确!python img2pdf.py
登录后复制
       
hec ['01.jpg', '02.jpg']
输出文件名称: 3D2.pdf
登录后复制
       
In [ ]
# 安装pyinstaller!pip install pyinstaller
登录后复制
       
Looking in indexes: https://mirror.baidu.com/pypi/simple/
Collecting pyinstaller
  Downloading https://mirror.baidu.com/pypi/packages/9e/ed/fbdad7f5d8f794c901076b814b8e9f5ce31d32c0bc3b63ddd27b61db9530/pyinstaller-4.1.tar.gz (3.5MB)
     |████████████████████████████████| 3.5MB 10.7MB/s eta 0:00:01
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... done
Collecting pyinstaller-hooks-contrib>=2020.6 (from pyinstaller)
  Downloading https://mirror.baidu.com/pypi/packages/a4/11/90ac24147907d9b7302983ec66ae46b045b47212906101cc82d9204c798d/pyinstaller_hooks_contrib-2020.11-py2.py3-none-any.whl (172kB)
     |████████████████████████████████| 174kB 26.8MB/s eta 0:00:01
Requirement already satisfied: setuptools in /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages (from pyinstaller) (41.4.0)
Collecting altgraph (from pyinstaller)
  Downloading https://mirror.baidu.com/pypi/packages/ee/3d/bfca21174b162f6ce674953f1b7a640c1498357fa6184776029557c25399/altgraph-0.17-py2.py3-none-any.whl
Building wheels for collected packages: pyinstaller
  Building wheel for pyinstaller (PEP 517) ... done
  Created wheel for pyinstaller: filename=pyinstaller-4.1-cp37-none-any.whl size=2790249 sha256=05cdd9cb8a71582013c50d28e248972bc8f80e6a03e802723f57994d6c0e8a6d
  Stored in directory: /home/aistudio/.cache/pip/wheels/fe/90/a2/7dc78a5ca953100aad6b663aae16db9962df27264f2d4ebb87
Successfully built pyinstaller
Installing collected packages: pyinstaller-hooks-contrib, altgraph, pyinstaller
Successfully installed altgraph-0.17 pyinstaller-4.1 pyinstaller-hooks-contrib-2020.11
登录后复制
       
In [ ]
# 打包!pyinstaller -F img2pdf.py
登录后复制
       
31 INFO: PyInstaller: 4.1
31 INFO: Python: 3.7.4 (conda)
32 INFO: Platform: Linux-4.4.0-166-generic-x86_64-with-debian-stretch-sid
32 INFO: wrote /home/aistudio/img2pdf.spec
34 INFO: UPX is not available.
35 INFO: Extending PYTHONPATH with paths
['/home/aistudio', '/home/aistudio']
45 INFO: checking Analysis
45 INFO: Building Analysis because Analysis-00.toc is non existent
45 INFO: Initializing module dependency graph...
47 INFO: Caching module graph hooks...
52 INFO: Analyzing base_library.zip ...
2593 INFO: Caching module dependency graph...
2657 INFO: running Analysis Analysis-00.toc
2671 INFO: Analyzing /home/aistudio/img2pdf.py
3330 INFO: Processing pre-find module path hook distutils from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks/pre_find_module_path/hook-distutils.py'.
3331 INFO: distutils: retargeting to non-venv dir '/opt/conda/envs/python35-paddle120-env/lib/python3.7'
4320 INFO: Processing pre-safe import module hook setuptools.extern.six.moves from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks/pre_safe_import_module/hook-setuptools.extern.six.moves.py'.
4664 INFO: Processing pre-find module path hook site from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks/pre_find_module_path/hook-site.py'.
4664 INFO: site: retargeting to fake-dir '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/fake-modules'
7977 INFO: Processing module hooks...
7977 INFO: Loading module hook 'hook-pycparser.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/_pyinstaller_hooks_contrib/hooks/stdhooks'...
7978 INFO: Loading module hook 'hook-difflib.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
7979 INFO: Excluding import of doctest from module difflib
7979 INFO: Loading module hook 'hook-heapq.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
7981 INFO: Excluding import of doctest from module heapq
7981 INFO: Loading module hook 'hook-numpy.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
7981 INFO: Loading module hook 'hook-setuptools.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8428 INFO: Excluding import of setuptools.py33compat from module setuptools.depends
8428 INFO: Excluding import of setuptools.py33compat from module setuptools.package_index
8430 INFO: Excluding import of setuptools.py27compat from module setuptools.command.easy_install
8430 INFO: Excluding import of setuptools.py27compat from module setuptools.package_index
8430 INFO: Loading module hook 'hook-pkg_resources.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8761 INFO: Processing pre-safe import module hook win32com from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/_pyinstaller_hooks_contrib/hooks/pre_safe_import_module/hook-win32com.py'.
8802 WARNING: Hidden import "pkg_resources.py2_warn" not found!
8802 WARNING: Hidden import "pkg_resources.markers" not found!
8804 INFO: Excluding import of __main__ from module pkg_resources
8805 INFO: Loading module hook 'hook-sysconfig.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8811 INFO: Loading module hook 'hook-distutils.util.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8812 INFO: Excluding import of lib2to3.refactor from module distutils.util
8813 INFO: Loading module hook 'hook-lib2to3.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8834 INFO: Loading module hook 'hook-numpy._pytesttester.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8836 INFO: Excluding import of pytest from module numpy._pytesttester
8836 INFO: Loading module hook 'hook-encodings.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8879 INFO: Loading module hook 'hook-xml.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8955 INFO: Loading module hook 'hook-scipy.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8955 INFO: Loading module hook 'hook-multiprocessing.util.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8956 INFO: Import to be excluded not found: 'test'
8957 INFO: Loading module hook 'hook-distutils.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
8957 INFO: Loading module hook 'hook-numpy.core.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9004 INFO: Loading module hook 'hook-PIL.Image.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9353 INFO: Loading module hook 'hook-PIL.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9356 INFO: Excluding import of tkinter from module PIL.ImageTk
9356 INFO: Import to be excluded not found: 'FixTk'
9357 INFO: Excluding import of PyQt5 from module PIL.ImageQt
9358 INFO: Loading module hook 'hook-xml.etree.cElementTree.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9358 INFO: Loading module hook 'hook-pickle.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9360 INFO: Excluding import of argparse from module pickle
9360 INFO: Loading module hook 'hook-PIL.ImageFilter.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9361 INFO: Excluding import of numpy from module PIL.ImageFilter
9362 INFO: Loading module hook 'hook-setuptools.msvc.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9363 INFO: Excluding import of numpy from module setuptools.msvc
9363 INFO: Loading module hook 'hook-_tkinter.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9441 INFO: checking Tree
9442 INFO: Building Tree because Tree-00.toc is non existent
9442 INFO: Building Tree Tree-00.toc
9448 INFO: checking Tree
9448 INFO: Building Tree because Tree-01.toc is non existent
9448 INFO: Building Tree Tree-01.toc
9488 INFO: checking Tree
9488 INFO: Building Tree because Tree-02.toc is non existent
9488 INFO: Building Tree Tree-02.toc
9491 INFO: Loading module hook 'hook-PIL.SpiderImagePlugin.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
9494 INFO: Import to be excluded not found: 'FixTk'
9509 INFO: Looking for ctypes DLLs
9576 INFO: Analyzing run-time hooks ...
9582 INFO: Including run-time hook '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks/rthooks/pyi_rth_multiprocessing.py'
9585 INFO: Including run-time hook '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pkgres.py'
9591 INFO: Looking for dynamic libraries
10343 INFO: Looking for eggs
10343 INFO: Python library not in binary dependencies. Doing additional searching...
10355 INFO: Using Python library /opt/conda/envs/python35-paddle120-env/lib/libpython3.7m.so.1.0
10363 INFO: Warnings written to /home/aistudio/build/img2pdf/warn-img2pdf.txt
10397 INFO: Graph cross-reference written to /home/aistudio/build/img2pdf/xref-img2pdf.html
10412 INFO: checking PYZ
10412 INFO: Building PYZ because PYZ-00.toc is non existent
10412 INFO: Building PYZ (ZlibArchive) /home/aistudio/build/img2pdf/PYZ-00.pyz
11198 INFO: Building PYZ (ZlibArchive) /home/aistudio/build/img2pdf/PYZ-00.pyz completed successfully.
11206 INFO: checking PKG
11206 INFO: Building PKG because PKG-00.toc is non existent
11206 INFO: Building PKG (CArchive) PKG-00.pkg
25664 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
25666 INFO: Bootloader /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/bootloader/Linux-64bit/run
25666 INFO: checking EXE
25666 INFO: Building EXE because EXE-00.toc is non existent
25666 INFO: Building EXE from EXE-00.toc
25667 INFO: Appending archive to ELF section in EXE /home/aistudio/dist/img2pdf
25697 INFO: Building EXE from EXE-00.toc completed successfully.
登录后复制
       

注意打包前后的变化:

豆包AI编程
豆包AI编程

豆包推出的AI编程助手

豆包AI编程483
查看详情 豆包AI编程

手把手教你用PyInstaller打包Python程序 - php中文网        

打包出来的文件就在dist目录下

In [ ]
# 测试打包结果,注意,由于python代码原因,pdf文件存到了dist目录下!cd dist && ./img2pdf
登录后复制
       
hec ['01.jpg', '02.jpg']
输出文件名称: 3D2.pdf
登录后复制
       

安装PYQT5依赖并打包

editor.py是一个简单的基于PYQT5实现的示例,尝试在Linux/Windows环境对其打包。

In [ ]
# 注意,pyqt5版本过高会报错,这里选了个不会报错的版本!pip install pyqt5==5.12.0
登录后复制
       
Looking in indexes: https://mirror.baidu.com/pypi/simple/
Collecting pyqt5==5.12.0
  Downloading https://mirror.baidu.com/pypi/packages/01/8c/eeff014306fcdbb8afda0fe603d1b458dddf2be0ca10d561b0015e439357/PyQt5-5.12-5.12.1_a-cp35.cp36.cp37.cp38-abi3-manylinux1_x86_64.whl (61.1MB)
     |████████████████████████████████| 61.1MB 8.5MB/s eta 0:00:01
Collecting PyQt5_sip<4.20,>=4.19.14 (from pyqt5==5.12.0)
  Downloading https://mirror.baidu.com/pypi/packages/bf/63/d363b567237375235d270049fd6416c83949f470bb51539458966cd7a38c/PyQt5_sip-4.19.19-cp37-cp37m-manylinux1_x86_64.whl (67kB)
     |████████████████████████████████| 71kB 13.5MB/s eta 0:00:01
Installing collected packages: PyQt5-sip, pyqt5
Successfully installed PyQt5-sip-4.19.19 pyqt5-5.12
登录后复制
       
In [ ]
!pyinstaller -F editor.py --hidden-import pyqt5
登录后复制
       
31 INFO: PyInstaller: 4.1
31 INFO: Python: 3.7.4 (conda)
31 INFO: Platform: Linux-4.4.0-166-generic-x86_64-with-debian-stretch-sid
31 INFO: wrote /home/aistudio/editor.spec
33 INFO: UPX is not available.
34 INFO: Extending PYTHONPATH with paths
['/home/aistudio', '/home/aistudio']
44 INFO: checking Analysis
44 INFO: Building Analysis because Analysis-00.toc is non existent
44 INFO: Initializing module dependency graph...
46 INFO: Caching module graph hooks...
51 INFO: Analyzing base_library.zip ...
2576 INFO: Caching module dependency graph...
2641 INFO: running Analysis Analysis-00.toc
2655 INFO: Analyzing /home/aistudio/editor.py
2684 INFO: Analyzing hidden import 'pyqt5'
2685 ERROR: Hidden import 'pyqt5' not found
2685 INFO: Processing module hooks...
2685 INFO: Loading module hook 'hook-PyQt5.QtCore.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
2759 INFO: Loading module hook 'hook-difflib.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
2760 INFO: Excluding import of doctest from module difflib
2761 INFO: Loading module hook 'hook-heapq.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
2761 INFO: Excluding import of doctest from module heapq
2761 INFO: Loading module hook 'hook-PyQt5.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
2772 WARNING: Hidden import "sip" not found!
2773 INFO: Loading module hook 'hook-PyQt5.QtWidgets.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
2859 INFO: Loading module hook 'hook-PyQt5.QtGui.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
2906 INFO: Loading module hook 'hook-encodings.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
2945 INFO: Loading module hook 'hook-xml.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
3143 INFO: Loading module hook 'hook-pickle.py' from '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks'...
3144 INFO: Excluding import of argparse from module pickle
3151 INFO: Looking for ctypes DLLs
3151 INFO: Analyzing run-time hooks ...
3153 INFO: Including run-time hook '/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/hooks/rthooks/pyi_rth_pyqt5.py'
3156 INFO: Looking for dynamic libraries
4859 INFO: Looking for eggs
4859 INFO: Python library not in binary dependencies. Doing additional searching...
4869 INFO: Using Python library /opt/conda/envs/python35-paddle120-env/lib/libpython3.7m.so.1.0
4872 INFO: Warnings written to /home/aistudio/build/editor/warn-editor.txt
4887 INFO: Graph cross-reference written to /home/aistudio/build/editor/xref-editor.html
4894 INFO: checking PYZ
4894 INFO: Building PYZ because PYZ-00.toc is non existent
4894 INFO: Building PYZ (ZlibArchive) /home/aistudio/build/editor/PYZ-00.pyz
5283 INFO: Building PYZ (ZlibArchive) /home/aistudio/build/editor/PYZ-00.pyz completed successfully.
5286 INFO: checking PKG
5286 INFO: Building PKG because PKG-00.toc is non existent
5286 INFO: Building PKG (CArchive) PKG-00.pkg
64713 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
64717 INFO: Bootloader /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/PyInstaller/bootloader/Linux-64bit/run
64717 INFO: checking EXE
64717 INFO: Building EXE because EXE-00.toc is non existent
64717 INFO: Building EXE from EXE-00.toc
64718 INFO: Appending archive to ELF section in EXE /home/aistudio/dist/editor
64865 INFO: Building EXE from EXE-00.toc completed successfully.
登录后复制
       

在Windows上打包也是相同的操作,最终效果如下,双击打开可执行文件,就能出现GUI界面了

手把手教你用PyInstaller打包Python程序 - php中文网        

手把手教你用PyInstaller打包Python程序 - php中文网        

这里给出打包过程日志供参考

(python37) F:labelImg>pyinstaller -F editor.py --hidden-import pyqt5
178 INFO: PyInstaller: 3.6
178 INFO: Python: 3.7.7 (conda)
180 INFO: Platform: Windows-10-10.0.18362-SP0
182 INFO: wrote F:labelImgeditor.spec
184 INFO: UPX is not available.
200 INFO: Extending PYTHONPATH with paths
['F:\', 'F:\labelImg']
208 INFO: checking Analysis
209 INFO: Building Analysis because Analysis-00.toc is non existent
209 INFO: Initializing module dependency graph...
215 INFO: Caching module graph hooks...
232 INFO: Analyzing base_library.zip ...
2196 INFO: Processing pre-find module path hook   distutils
2199 INFO: distutils: retargeting to non-venv dir 'C:\Users\user\anaconda3\envs\python37\lib'3772 INFO: Caching module dependency graph...
3882 INFO: running Analysis Analysis-00.toc
3900 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by C:Usersusernaconda3envspython37python.exe
4426 INFO: Analyzing F:labelImgeditor.py
4482 INFO: Analyzing hidden import 'pyqt5'4483 ERROR: Hidden import 'pyqt5' not found
4483 INFO: Processing module hooks...
4483 INFO: Loading module hook "hook-distutils.py"...
4486 INFO: Loading module hook "hook-encodings.py"...
4567 INFO: Loading module hook "hook-pydoc.py"...
4569 INFO: Loading module hook "hook-PyQt5.py"...
4800 INFO: Loading module hook "hook-PyQt5.QtCore.py"...
4932 INFO: Loading module hook "hook-PyQt5.QtGui.py"...
5143 INFO: Loading module hook "hook-PyQt5.QtWidgets.py"...
5429 INFO: Loading module hook "hook-sysconfig.py"...
5432 INFO: Loading module hook "hook-xml.py"...
5695 INFO: Looking for ctypes DLLs
5696 INFO: Analyzing run-time hooks ...
5698 INFO: Including run-time hook 'pyi_rth_pyqt5.py'5709 INFO: Looking for dynamic libraries
6959 INFO: Looking for eggs
6959 INFO: Using Python library C:Usersusernaconda3envspython37python37.dll
6960 INFO: Found binding redirects:
[]
6977 INFO: Warnings written to F:labelImguildeditorwarn-editor.txt
7014 INFO: Graph cross-reference written to F:labelImguildeditorxref-editor.html
7043 INFO: checking PYZ
7044 INFO: Building PYZ because PYZ-00.toc is non existent
7044 INFO: Building PYZ (ZlibArchive) F:labelImguildeditorPYZ-00.pyz
7410 INFO: Building PYZ (ZlibArchive) F:labelImguildeditorPYZ-00.pyz completed successfully.
7422 INFO: checking PKG
7422 INFO: Building PKG because PKG-00.toc is non existent
7422 INFO: Building PKG (CArchive) PKG-00.pkg
18126 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
18133 INFO: Bootloader C:Usersusernaconda3envspython37libsite-packagesPyInstallerootloaderWindows-64bit
un.exe
18133 INFO: checking EXE
18133 INFO: Building EXE because EXE-00.toc is non existent
18133 INFO: Building EXE from EXE-00.toc
18134 INFO: Appending archive to EXE F:labelImgdisteditor.exe
18240 INFO: Building EXE from EXE-00.toc completed successfully.
登录后复制
   

OCR截图项目的打包

OCR截图小工具的打包,涉及到4个小知识点,分别是:

- 多文件处理 —— 其实就是在命令行里把3个python文件都写进去

- UI资源文件处理 —— 使用--add-data设置

- 精简依赖处理 —— 尽量不要直接import,能from……import……就这么写;强烈不建议直接打包飞桨套件,改为API调用

- import路径调整的处理 —— 为什么打包后会闪退?原来前面的操作会导致打包后inference目录下的两个文件跑到当前目录来了

因此,最终打包命令就是:

pyinstaller -F --add-data="interface/interface.ui;." main.py screen_rec.py interface/interface.py
登录后复制
   
In [ ]
# 解压查看截图识别助手源代码!unzip data/data57331/ScreenRec.zip -d ./work/
登录后复制
       
Archive:  data/data57331/ScreenRec.zip
   creating: ./work/ScreenRec/
  inflating: ./work/ScreenRec/README.md  
  inflating: ./work/ScreenRec/Shapely-1.7.1-cp37-cp37m-win_amd64.whl  
   creating: ./work/ScreenRec/interface/
  inflating: ./work/ScreenRec/interface/interface.py  
  inflating: ./work/ScreenRec/interface/interface.ui  
  inflating: ./work/ScreenRec/main.py  
  inflating: ./work/ScreenRec/requirements.txt  
  inflating: ./work/ScreenRec/screen_rec.py
登录后复制
       
In [ ]
# 尝试直接打包,注意,在linux中--add-data的写法!cd work/ScreenRec && pyinstaller -F --add-data="interface/interface.ui:." main.py screen_rec.py interface/interface.py
登录后复制
   

我们会发现,执行时间会非常长,因为源代码中有一句import paddlehub as hub,等于需要把paddlehub,paddlepaddle,paddlepaddle的依赖统统打包…… 那么,有没有快一点的办法?当然有,其实源代码中也给出了解决方案,就是screen_rec.py这里:

    # 使用PPOCR识别截图,返回识别结果
    def imrec(self, img):
        # 判断 识别方式
        if self._way == "0":
            ocr = hub.Module(name="chinese_ocr_db_crnn_mobile")
            result = ocr.recognize_text(images=[img])
            res = str()            for data in result[0]["data"]:
                res += data["text"]                # 判断 是否需要保留样式
                if self._keepStyle:
                    res += "
"

        elif self._way == "1" or "2":
            result = self.baiduAPI(img)
            res = str()            for words in result["words_result"]:
                res += words["words"]                if self._keepStyle:
                    res += "
"
        return res
登录后复制
       

也就是说,我们可以选择用百度API进行识别,比如到通用场景文字识别申请一个API_Key和Secret_Key,替换掉源代码中的内容(源代码的KEY已经不能用了),然后注释掉import paddlehub as hub,删除本地模式等。

手把手教你用PyInstaller打包Python程序 - php中文网每天500次免费调用量,还是够用的吧手把手教你用PyInstaller打包Python程序 - php中文网如果懒得改太多代码,该文件只需要改前几行即可:

# 打包导致路径变化,需修改# from interface.interface import Ui_MainWindowfrom interface import Ui_MainWindowfrom PIL import Image, ImageGrabimport cv2import numpy as npfrom PyQt5.QtWidgets import QMainWindow# 注释掉# import paddlehub as hub import requestsimport base64import pyperclipfrom datetime import datetimeclass run(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self._keepStyle = False
        self._toClipboard = True
        self._way = "1"  # 默认走API预测
        self.API_Key = "lvM38ECpObMh25YY2qd7vc7R" # 请换成读者自己的KEY
        self.Secret_Key = "qQG1Do5I8fZivvCiFCchXnQFI8aNGymd"  # 请换成读者自己的KEY
登录后复制
       

同样的main.py因为打包路径的问题,也要做一些修改,将from interface import interface改为import interface

In [7]
!cd work/ScreenRec && pyinstaller -F --add-data="interface/interface.ui:." main.py screen_rec.py interface/interface.py
登录后复制
   

Windows环境打包

打包后运行时查看日志:通过命令行运行可执行程序,可以debug用

手把手教你用PyInstaller打包Python程序 - php中文网        

打包成功效果展示

手把手教你用PyInstaller打包Python程序 - php中文网        

打包过程日志——日志告诉我们,WARNING不会影响打包结果,这些lib找不到没关系

(python37) F:ScreenRec>pyinstaller -F --add-data="interface/interface.ui;." main.py screen_rec.py interface/interface.py
73 INFO: PyInstaller: 3.6
74 INFO: Python: 3.7.7 (conda)
74 INFO: Platform: Windows-10-10.0.18362-SP0
77 INFO: wrote F:ScreenRecmain.spec
79 INFO: UPX is not available.
80 INFO: Extending PYTHONPATH with paths
['F:\ScreenRec', 'F:\ScreenRec', 'F:\ScreenRec\interface', 'F:\ScreenRec']
81 INFO: checking Analysis
81 INFO: Building Analysis because Analysis-00.toc is non existent
81 INFO: Initializing module dependency graph...
85 INFO: Caching module graph hooks...
91 INFO: Analyzing base_library.zip ...
1772 INFO: Processing pre-find module path hook   distutils
1773 INFO: distutils: retargeting to non-venv dir 'C:\Users\user\anaconda3\envs\python37\lib'3015 INFO: Caching module dependency graph...
3131 INFO: running Analysis Analysis-00.toc
3150 INFO: Adding Microsoft.Windows.Common-Controls to dependent assemblies of final executable
  required by C:Usersusernaconda3envspython37python.exe
3444 INFO: Analyzing F:ScreenRecmain.py
5367 INFO: Processing pre-safe import module hook   setuptools.extern.six.moves
5857 INFO: Processing pre-find module path hook   site
5858 INFO: site: retargeting to fake-dir 'C:\Users\user\anaconda3\envs\python37\lib\site-packages\PyInstaller\fake-modules'9944 INFO: Processing pre-safe import module hook   urllib3.packages.six.moves
11342 INFO: Processing pre-safe import module hook   six.moves
12213 INFO: Analyzing F:ScreenRecscreen_rec.py
12217 INFO: Analyzing F:ScreenRecinterfaceinterface.py
12221 INFO: Processing module hooks...
12222 INFO: Loading module hook "hook-certifi.py"...
12224 INFO: Loading module hook "hook-cryptography.py"...
12481 INFO: Loading module hook "hook-cv2.py"...
12482 INFO: Loading module hook "hook-distutils.py"...
12483 INFO: Loading module hook "hook-encodings.py"...
12563 INFO: Loading module hook "hook-lib2to3.py"...
12567 INFO: Loading module hook "hook-numpy.core.py"...
12674 INFO: MKL libraries found when importing numpy. Adding MKL to binaries
12678 INFO: Loading module hook "hook-numpy.py"...
12679 INFO: Loading module hook "hook-PIL.Image.py"...
13145 INFO: Loading module hook "hook-PIL.py"...
13147 INFO: Excluding import 'PyQt4'13149 INFO: Excluding import 'tkinter'13151 INFO:   Removing import of tkinter from module PIL.ImageTk
13152 INFO: Excluding import 'PyQt5'13153 INFO:   Removing import of PyQt5.QtGui from module PIL.ImageQt
13157 INFO:   Removing import of PyQt5.QtCore from module PIL.ImageQt
13158 INFO: Import to be excluded not found: 'PySide'13158 INFO: Import to be excluded not found: 'FixTk'13158 INFO: Loading module hook "hook-PIL.SpiderImagePlugin.py"...
13160 INFO: Excluding import 'tkinter'13161 INFO: Import to be excluded not found: 'FixTk'13162 INFO: Loading module hook "hook-pkg_resources.py"...
13641 INFO: Processing pre-safe import module hook   win32com
13903 INFO: Excluding import '__main__'13905 INFO:   Removing import of __main__ from module pkg_resources
13906 INFO: Loading module hook "hook-pycparser.py"...
13909 INFO: Loading module hook "hook-pydoc.py"...
13910 INFO: Loading module hook "hook-PyQt5.py"...
14051 INFO: Loading module hook "hook-PyQt5.QtCore.py"...
14139 INFO: Loading module hook "hook-PyQt5.QtGui.py"...
14351 INFO: Loading module hook "hook-PyQt5.QtWidgets.py"...
14630 INFO: Loading module hook "hook-pythoncom.py"...
15042 INFO: Loading module hook "hook-pywintypes.py"...
15451 INFO: Loading module hook "hook-scipy.py"...
15454 INFO: Loading module hook "hook-setuptools.py"...
16103 INFO: Loading module hook "hook-sysconfig.py"...
16105 INFO: Loading module hook "hook-win32com.py"...
16629 INFO: Loading module hook "hook-xml.py"...
16709 INFO: Loading module hook "hook-_tkinter.py"...
16881 INFO: checking Tree
16881 INFO: Building Tree because Tree-00.toc is non existent
16881 INFO: Building Tree Tree-00.toc
16956 INFO: checking Tree
16957 INFO: Building Tree because Tree-01.toc is non existent
16957 INFO: Building Tree Tree-01.toc
17013 INFO: Looking for ctypes DLLs
17051 INFO: Analyzing run-time hooks ...
17057 INFO: Including run-time hook 'pyi_rth_pyqt5.py'17059 INFO: Including run-time hook 'pyi_rth_certifi.py'17060 INFO: Including run-time hook 'pyi_rth_pkgres.py'17062 INFO: Including run-time hook 'pyi_rth_win32comgenpy.py'17064 INFO: Including run-time hook 'pyi_rth_multiprocessing.py'17079 INFO: Looking for dynamic libraries
17392 WARNING: lib not found: pgc14.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_pgi_thread.dll
17394 WARNING: lib not found: pgf90.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_pgi_thread.dll
17395 WARNING: lib not found: pgf90rtl.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_pgi_thread.dll
17412 WARNING: lib not found: impi.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_blacs_intelmpi_ilp64.dll
17467 WARNING: lib not found: msmpi.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_blacs_msmpi_ilp64.dll
17583 WARNING: lib not found: mpich2mpi.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_blacs_mpich2_ilp64.dll
17637 WARNING: lib not found: mpich2mpi.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_blacs_mpich2_lp64.dll
17685 WARNING: lib not found: msmpi.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_blacs_msmpi_lp64.dll
17929 WARNING: lib not found: impi.dll dependency of C:Usersusernaconda3envspython37Libraryinmkl_blacs_intelmpi_lp64.dll
19020 INFO: Looking for eggs
19021 INFO: Using Python library C:Usersusernaconda3envspython37python37.dll
19021 INFO: Found binding redirects:
[]
19033 INFO: Warnings written to F:ScreenRecuildmainwarn-main.txt
19146 INFO: Graph cross-reference written to F:ScreenRecuildmainxref-main.html
19187 INFO: Appending 'datas' from .spec
19190 INFO: checking PYZ
19192 INFO: Building PYZ because PYZ-00.toc is non existent
19192 INFO: Building PYZ (ZlibArchive) F:ScreenRecuildmainPYZ-00.pyz
20632 INFO: Building PYZ (ZlibArchive) F:ScreenRecuildmainPYZ-00.pyz completed successfully.
20664 INFO: checking PKG
20665 INFO: Building PKG because PKG-00.toc is non existent
20665 INFO: Building PKG (CArchive) PKG-00.pkg
95134 INFO: Building PKG (CArchive) PKG-00.pkg completed successfully.
95144 INFO: Bootloader C:Usersusernaconda3envspython37libsite-packagesPyInstallerootloaderWindows-64bit
un.exe
95145 INFO: checking EXE
95145 INFO: Building EXE because EXE-00.toc is non existent
95145 INFO: Building EXE from EXE-00.toc
95146 INFO: Appending archive to EXE F:ScreenRecdistmain.exe
96407 INFO: Building EXE from EXE-00.toc completed successfully.
登录后复制
   

以上就是手把手教你用PyInstaller打包Python程序的详细内容,更多请关注php中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号