pyinstaller 打包exe有依赖文件 py文件、dll文件、外部参数txt、json文件

您所在的位置:网站首页 python如何将代码打包成exe文件 pyinstaller 打包exe有依赖文件 py文件、dll文件、外部参数txt、json文件

pyinstaller 打包exe有依赖文件 py文件、dll文件、外部参数txt、json文件

2024-07-10 05:51| 来源: 网络整理| 查看: 265

pyinstaller的打包依赖问题,主要可以分为三大类 : 1、打包某个文件夹下的某一个py文件 2、打包某个文件夹下的几个py文件 3、打包不同文件下需读入外部参数txt、json等

本人的相关配置

python3.6 anaconda win-32(因为程序需要32位) 文件夹所在位置:

C:\\Users\\ASUS\\Desktop\\Conbination

文件结构如下图所示 在这里插入图片描述

打包前须知

1、除python自带的模块、包之外(自带是指,pip install xxx 安装上的),其他的例如dll文件类,pyinstaller不负责打包进去,所以需要指定文件所在路径。帮助打包,否则importerror。 2、所有的外部参数,都可以在第一次打包后的scripts文件夹下的spec文件内修改。 在这里插入图片描述

打包某个文件夹下的某一个py文件

1、打包test_1.py文件

>>scripts>>pyinstaller -F -w test_1.py

-F 打包成一个独立的exe文件,无其他 -w不显示控制台[依据个人需求,看是否需要-w] 若test_1.py内有

import need_out import need1.dll

则,打开scripts文件夹下的 test_1.spec(用python编辑器打开即可) 将datas=[]更改为need_out.dll的路径

# -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis(['test_1.py'], pathex=[], binaries=[], datas=[('C:\\Users\\ASUS\\Desktop\\Conbination\\need_out.dll','.'), ('C:\\Users\\ASUS\\Desktop\\Conbination\\test\\need1.dll','.')], hiddenimports=[], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False)

若打包成功后的exe执行时发现显示“NoModuleNamed…”或者显示找不到dll,则继续将dll的文件路径添加到pathex内:

pathex=['C:\\Users\\ASUS\\Desktop\\Conbination\\test','C:\\Users\\ASUS\\Desktop\\Conbination']

修改.spec文件后保存,然后执行

scripts>>pyinstaller -F test_1.spec 打包某个文件夹下的几个py文件

主程序为:test_2.py,但是需要用到class_for_test_2_1.py 和class_for_test_2_2.py 则,首先

scripts>>pyinstaller -F test_2.py

再在生成的test_2.spec文件中修改

a = Analysis(['test_2.py']

此处继续添加其他py文件

a = Analysis(['test_2.py', 'C:\\Users\\ASUS\\Desktop\\Conbination\\test\\class_for_test_2_1.py', 'C:\\Users\\ASUS\\Desktop\\Conbination\\test\\class_for_test_2_2.py'], ... ... ...

最后执行:

scripts>>pyinstaller -F test_2.spec 打包不同文件下需读入外部参数txt、json等

1、py文件内凡涉及到读取外部文件数据时,不可用相对路径,否则执行exe时,会显示找不到json文件 eg:我的test_2.py文件需要用到for_test_2_json.json文件 则在编写test_2.py时,最好用以下方法:

import json cur_path = os.path.abspath(__file__) parent_path = os.path.abspath(os.path.dirname(cur_path) + os.path.sep + "..") file_path = os.path.join(parent_path,'util\\for_test_2_json.json') print("外部文件路径:"+file_path) with open(file_path,'r', encoding='UTF-8') as f: load_dict = json.load(f)

也可以用其他的方法:

https://blog.csdn.net/Iv_zzy/article/details/107407167

test_2.py的全部执行过程为:

scripts>>pyinstaller -F test_2.py a = Analysis(['test_2.py', 'C:\\Users\\ASUS\\Desktop\\Conbination\\test\\class_for_test_2_1.py', 'C:\\Users\\ASUS\\Desktop\\Conbination\\test\\class_for_test_2_2.py'], pathex=['C:\\Users\\ASUS\\Desktop\\Conbination\\test','C:\\Users\\ASUS\\Desktop\\Conbination'] datas=[('C:\\Users\\ASUS\\Desktop\\Conbination\\need_out.dll','.'), ('C:\\Users\\ASUS\\Desktop\\Conbination\\test\\need1.dll','.')], scripts>>pyinstaller -F test_2.spec

好啦,先介绍到这儿,后面再有其他的再继续补充~



【本文地址】


今日新闻


推荐新闻


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