# PyInstaller基本使用方法

# PyInstaller 打包参数

# -F -D互斥参数
-F  打包成一个exe文件,小项目可以采用,打开比较慢,多个.py打包时不能使用
-D  默认参数,打包结果放入到创建的文件夹中,可以看到里面有很多的依赖文件
 
# -w -c互斥参数
-w  使用项目的GUI界面,无cmd控制台
-c  默认参数,使用cmd控制台 如果打包文件执行报错,可尝试用-c 显示控制台
 
-n  执行项目的名称,默认.py的文件名
-i  将ico图标打包到exe文件中
 
--hidden-import 打包时导包信息
# 打包PyQt项目强烈建议 带上以下参数
--hidden-import PyQt5.sip
 
# 打包命令示例
# 在项目的根目录下执行打包命令
pyinstaller -w xxx.py --hidden-import PyQt5.sip
  
# 打包结果输出在项目根目录下的 dist文件夹中
# 不建议使用 -F打包成一个exe文件 所谓:打包一时爽,打开5秒钟
# 非-F命令下, 静态资源、建好的Sqlite数据库可以直接放入dist中 生成的文件夹中

# Venv 环境打包

在 venv 环境打包可以避免打包无关内容进来,但是要注意在 venv 环境安装 pyinstaller,否则不生效。

# 创建 venv 环境
python3 -m venv venv

# pip 升级
pip install --upgrade pip

# pip 安装 pyinstaller
pip install pyinstaller

# 系统找不到 subprocess.py 文件错误

错误提示如下:

File "subprocess.py", line 951, in __init__
File "subprocess.py", line 1420, in _execute_child
FileNotFoundError: [WinError 2] 系统找不到指定的文件。
[20684] Failed to execute script 'main' due to unhandled exception!

该错误出现的原因为 subprocess.Popen 参数不全导致,找到报错的文件,将该方法参数补全即可解决

# 简略参数
proc = subprocess.Popen("./sub.bat", cwd=getpath, stdout=subprocess.PIPE)

# 完整参数
proc = subprocess.Popen("./sub.bat", cwd=getpath, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

# Paddle 打包时 \paddle\dataset\image.py 文件报 subprocess.py文件错误

修改 image.py 文件

# \site-packages\paddle\dataset\image.py
if six.PY3:
    import subprocess
    import sys
    import os
    interpreter = sys.executable
    # Note(zhouwei): if use Python/C 'PyRun_SimpleString', 'sys.executable'
    # will be the C++ execubable on Windows
    if sys.platform == 'win32' and 'python.exe' not in interpreter:
        interpreter = sys.exec_prefix + os.sep + 'python.exe'
    import_cv2_proc = subprocess.Popen(
        [interpreter, "-c", "import cv2"],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    out, err = import_cv2_proc.communicate()
    retcode = import_cv2_proc.poll()
    if retcode != 0:
        cv2 = None
    else:
        import cv2
else:
    try:
        import cv2
    except ImportError:
        cv2 = None

改为

try:
    import cv2
except ImportError:
    cv2 = None