Pyinstaller打包数据文件或配置文件的简单说明

您所在的位置:网站首页 python数据文件输入输出 Pyinstaller打包数据文件或配置文件的简单说明

Pyinstaller打包数据文件或配置文件的简单说明

2023-10-07 01:51| 来源: 网络整理| 查看: 265

官网: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

start 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 existWrites some log files and working files in the build folderCreates a folder dist in the same folder as the script if it does not existWrites 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 手工修改上述spec文件,仅调整datas列表参数,其他地方不动。 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 nowThe second specifies the name of the folder to contain the files at run-time

使用spec文件执行生成可执行程序命令

pyinstaller student.spec

install

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



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3