官网:http://www.pyinstaller.org/
PyInstaller freezes (packages) Python applications into stand-alone executables, under Windows, GNU/Linux, Mac OS X, FreeBSD, Solaris and AIX.
我本地程序文件说明:同一个目录【E:\pytest\student】下两个文件,一个.py,一个.txt文本文件;py程序读写txt文件。
我们的py程序也许用到了其他配置文件(properties/conf),如何将这些文件也打包到执行程序中呢?
安装
pip install pyinstaller
Quickstart
PyInstaller analyzes yourprogram.py and:
- Writes yourprogram.spec in the same folder as the script(生成spec文件)
- Creates a folder build in the same folder as the script if it does not exist
- Writes some log files and working files in the build folder
- Creates a folder dist in the same folder as the script if it does not exist
- Writes the yourprogram executable folder in the dist folder
In the dist folder you find the bundled app you distribute to your users
数据(或配置)文件
在spec文件中,手工写入数据文件等路径,然后通过spec生成可执行程序。
0、生成spec文件
The spec file tells PyInstaller how to process your script. It encodes the script names and most of the options you give to the pyinstaller command. The spec file is actually executable Python code. PyInstaller builds the app by executing the contents of the spec file.
可以使用下面两种方式,推荐第二种
pyinstaller yourprogram.py
或
pyinstaller -makespec yourprogram.py
1、文件夹形式的可执行程序
-D, Create a one-folder bundle containing an executable (default)
pyinstaller -D student.py
手工修改上述spec文件,仅调整datas列表参数,其他地方不动。
修改说明:
Each tuple has two values, both of which must be strings:
- The first string specifies the file or files as they are in this system now
- The second specifies the name of the folder to contain the files at run-time
使用spec文件执行生成可执行程序命令
pyinstaller student.spec
2、单个文件形式的可执行程序
基本步骤同上,仅需将参数-D,调整为-F(pyinstaller -F student.py)
但因为单个exe文件类似zip文件,运行时有解压动作。故此需要修改源码,即:读写txt文件代码。
文件夹形式的源代码:
open('students.txt', 'a')
单文件形式的源代码:
open(resource_path('students.txt'), 'a')
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
return os.path.join(base_path, relative_path)
本文示例使用的是文本文件,如果二进制文件怎么处理?更多spec文件用法,大家参考官方:
https://pyinstaller.readthedocs.io/en/stable/spec-files.html