标签归档:Python

使用 PyInstaller 把python程序 .py转为 .exe 可执行程序

最近使用Python为项目开发一款绘图工具(绘出 声场三维模型)。因为希望能把Python脚本发布为脱离Python平台运行的可执行程序,比如单个的exe文件。PyInstaller恰满足这个需求。本文PyInstaller的版本是2.0,支持Python2.7。下面讨论怎样安装,使用PyInstaller。PyInstaller本身并不属于Python包。在安装 pyinstaller 之前假设你已经安装了python ,注意把python 环境变量配置好, 即 进入cmd后 输入 python 会进入 python shell.
pyinstaller安装:
1,下载pyinstaller并解压(可以去官网下载最新版):
2,安装最新版本的 pywin32-217.win32-py2.7.exe:
不然会出现错误Error: PyInstaller for Python 2.6+ on Windows needs pywin32.
3,进入cmd ,
d:\>cd d:\PyInstaller-2.1
d:\pyinstaller>python pyinstaller.py
Usage: python pyinstaller.py [opts] <scriptname> [ <scriptname> ...] | <specfile>
pyinstaller.py: error: Requires at least one scriptname file or exactly one .spec-file
以上信息表示可以开展工作了,以下是测试一个demo.py 文件的打包,文件放在当前目录的pyinstaller-2.1文件夹里面 .
d:\pyinstaller-2.1>python pyinstaller.py --console --onefile demo.py

上面的命令成功运行后demo.py 会生成一个demo文件夹。在这个文件夹下面会有一个名为dist的文件夹,此文件夹下面有转换好的demo.exe。

1

点击 demo.exe,首先会出来一个 控制台的黑窗口,如下图:

2
4, 上面编译出来的exe能够正常运行了,但带一个黑色的console,以下重新编译,加入--windowed --icon,取消--console
D:\PyInstaller-2.1>python pyinstaller.py -w --onefile --icon="my.ico" demo.py
icon是你喜欢的图标文件,py为你要打包的程序。最后生成一个demo.exe可执行文件,点击demo.exe直接显示所绘图形。

3