kevinc

主攻ZYNQ及RTOS开发,关注Flash存储

将python文件打包成exe可执行文件

0
阅读(2708)

目标:将python打包成在windows上能执行的.exe文件

环境: Win7-64bit python3.5.1 pyqt5.6


一、选择工具

网上介绍的常用工具有两个:py2exe,  pyinstaller(重点)

1、py2exe

这个网上介绍的最多。

官网最新版本:py2exe 0.9.2.2 ,上传日期2014-10-21。(https://pypi.python.org/pypi/py2exe)

最新只支持到py3.4。我在py3.5上跑代码,直接报错找不到3.5的run文件。只能作罢!




2、pyinstaller

官网介绍很诱人:http://www.pyinstaller.org/


  • Multiplatform: works under

    • Windows (32-bit and 64-bit),

    • Linux (32-bit and 64-bit),

    • Mac OS X (32-bit and 64-bit),

    • contributed suppport for FreeBSD, Solaris and AIX.

  • Multiversion: supports Python 2.7 and Python 3.3, 3.4 and 3.5.

  • Flexible packaging mode:

    • Single directory: build a directory containing an executable plus all the external binary modules (.dll, .pyd, .so) used by the program.

    • Single file: build a single executable file, totally self-contained, which runs without any external dependency.

    • Custom: you can automate PyInstaller to do whatever packaging mode you want through a simple script file in Python.

我只打算用最新版本py3.5 pyQt5.6,所以重点攻这个。


直接用终端在线安装   pip install pyinstaller

工具会自动关联安装setuptools 和 pypiwin32,赞。




二、打包过程

学习文档


Documentation:https://pythonhosted.org/PyInstaller/
Website:http://www.pyinstaller.org

 打包过程非常简单:只需要执行 pyinstaller -F xxxxx.py 即可


示例如下:

1、写个Qt小代码:先终端打印两句话,然后弹出个小窗口。IDE执行成功。


[python] view plain copy

  1. import sys    

  2. from PyQt5 import QtWidgets, QtCore    

  3. # 调试打印    

  4. print("这是第一句")    

  5. print("这是第二句")    

  6. # 显示hello窗口    

  7. app = QtWidgets.QApplication(sys.argv)    

  8. widget = QtWidgets.QWidget()    

  9. widget.resize(300100)    

  10. widget.setWindowTitle("Hello, PyQt5!")    

  11. widget.show()    

  12. sys.exit(app.exec_())   


2、终端定位到该目录,输入pyinstaller -F xxxxx.py

在dist目录下有一个.exe文件,双击在本机可以执行。跟解释器的结果一致。





三、问题定位

1、这个小程序居然生成了17.7MB的文件。太大了!  其实打包的基本原理就是把相关库文件都bundle进去,Qt本身就比较大。

(网上说wxPython做的UI要小很多,待尝试对比。)


2、在其他机子上,没装python,运行报错!

---- 这些都是MS的运行库,我们装的好多win系统都是做了删减的ghost,没有这些。 

----解决办法很简单,从MS官网下个Visual C++ Redistributable for Visual Studio 2015 只有14MB,在目标机上安装就哦了。



解决upx压缩问题。

在upx官网下载其upx.exe,放到python安装目录(因为这是PATH路径)。再次执行pyinstaller -F xxxx.py

这次找到了UPX,最终文件是13.7MB(小了一点)。


貌似这次也调入了api-ms-win-crt-runtime等文件。



但是最终文件在本机都不能顺利执行!

这次又成了没找到Qt platform plugin中的windows插件。改回到不用upx: pyinstaller -F --noupx xxxx.py,回到第一步。两难!


警告Qt的这些class都加不上。



最终定位为这个叫windows的平台插件找不到。

解决方式如下:将链接库路径D:\Python35\Lib\site-packages\PyQt5\Qt\plugins\platforms附在-p关联路径中,同时将该platforms文件夹copy到.exe同级目录下。

这次执行  pyinstaller hello.py -F -p D:\Python35\Lib\site-packages\PyQt5\Qt\plugins\platforms 完全OK。

接下来,到其他没有python的机子上再试。




写在最后

将.py文件转成.exe文件属于程序发布的概念。这个跟程序设置&运行系统都有关系,并非简单操作。

解决类似问题的方法:

1、搞定所有问题,务必整成.exe文件;

2、在所有目标机上安装python及三方modules,搭建.py运行环境。