http://blog.csdn.net/pipisorry/article/details/50620495

目录结构

 

将主文件testMain.py转换成exe可执行文件

主文件调用了自定义包:nlptest,其中nlptest1.py读取文件stopwordsFile.txt。

错误1:[Errno 2] No such file or directory: 'C:\Users\...\AppData\Local\Temp\_MEI***'

问题:

这个问题实质上是python代码转换成exe时怎么添加数据文件[http://pythonhosted.org/PyInstaller/#adding-data-files]

python文件通过命令$pyinstaller -F E:/mine/python_workspace/NLP/TargetOpinion/TargetOpinionMain.py转换为exe文件时数据文件找不到[pyinstaller使用-python项目转换成exe可执行文件]
原来python文件中读取路径为stopwordsFile的文件with open(stopwordsFile, encoding='utf-8')as f

转换为exe后,只有一个exe文件了,exe文件执行时,会将资源释放到temp文件夹下再执行,但是原来的数据文件stopwordsFile并没打包和释放,这样就会找不到文件。

原因详解:

单独生成一个exe文件(-F参数)后,exe文件是怎么运行的:

How the One-File Program Works
The bootloader is the heart of the one-file bundle also. When started it creates a temporary folder in the appropriate temp-folder location for this OS. The folder is named _MEIxxxxxx, where xxxxxx is a random number.
The one executable file contains an embedded archive of all the Python modules used by your script, as well as compressed copies of any non-Python support files (e.g. .so files). The bootloader uncompresses the support files and writes copies into the the temporary folder. This can take a little time. That is why a one-file app is a little slower to start than a one-folder app.
After creating the temporary folder, the bootloader proceeds exactly as for the one-folder bundle, in the context of the temporary folder. When the bundled code terminates, the bootloader deletes the temporary folder.

[http://pythonhosted.org/PyInstaller/#how-the-one-file-program-works]

解决方案:

方案1:

最后发现比较简单的解决方案只要将python代码中的数据文件拷贝到dist文件夹下,如dist/data/stopwordsFile.txt,在python代码中读取文件时文件路径为stopwordsFile=r"data/stopwordsFile.txt"就可以了。

为了python代码直接执行和exe执行都不会出错,可以这样写代码

添加一个判断,如果是pyinstaller生成的exe文件执行的,会在sys中(之前版本是这个os.environ?)添加一个_MEIPASS(即exe释放路径C:\Users\...\AppData\Local\Temp\_MEI***)和一个frozen [It also adds the attributesfrozenand_MEIPASSto thesysbuilt-in module],直接从python代码执行则不会

analysis.py


    if getattr(sys, 'frozen', False):pathname =r""else:pathname =os.path.split(os.path.realpath(__file__))[0]print("pathname: "+pathname)stopwordsFile =GlobalOptions.stopwordsFilestopwordsFile =os.path.join(pathname, stopwordsFile)

class GlobalOptions():'''全局变量设置'''# 如果用pyinstaller转换后,对应于exe文件的dist目录,下面的文件要要放在exe同目录下stopwordsFile =r'data/English_stopwords.txt'

要保证在dist/data目录下存在数据文件,并且python执行时analysis.py同目录下/data目录中也有数据文件,这样不管exe执行还是python代码执行都找得到数据文件。

[pyinstaller打包selenium找不到webdriver_prefs.json]

方案2:(目前推荐这个,有更好的方案lz会更新)

修改中间文件,再去生成exe文件,这样生成exe文件时将python项目中的数据文件加入到生成的exe bundle的文件中,exe文件执行时,会释放txt文件到temp目录下。

为了python代码直接执行和exe执行都不会出错,可以这样写代码:

添加一个判断,如果是pyinstaller生成的exe文件执行的,会在sys中(之前版本是这个os.environ?)添加一个_MEIPASS(即exe释放路径C:\Users\...\AppData\Local\Temp\_MEI***),数据文件也会在这个目录下。和一个frozen [It also adds the attributesfrozenand_MEIPASSto thesysbuilt-in module],直接从python代码执行则不会。

analysis.py:

if getattr(sys, 'frozen', False):pathname =sys._MEIPASS
else:pathname =os.path.split(os.path.realpath(__file__))[0]
# print("pathname: " + pathname)patternFile =GlobalOptions.patternFile
patternFile =os.path.join(pathname, patternFile)with open(stopwordsFile, encoding='utf-8')as f: ...

Note: lz要提醒的是:os.path.split(os.path.realpath(__file__))[0]这个路径在exe文件中实际就是C:\Users\...\AppData\Local\Temp\_MEI***\test0\nlptest也就是路径sys._MEIPASS\python项目顶层目录\...\analysis.py

[http://pythonhosted.org/PyInstaller/#using-file-and-sys-meipass]

[PyInstaller: IOError: [Errno 2] No such file or directory]

[PyInstaller executable issue]

1. 同方案1在原来的python项目读取数据文件的pythony文件中添加一个判断,如果是pyinstaller生成的exe文件执行的,会在sys中添加一个_MEIPASS(即exe释放路径C:\Users\...\AppData\Local\Temp\_MEI***)和一个frozen [It also adds the attributesfrozenand_MEIPASSto thesysbuilt-in module],直接从python代码执行则不会

2. 修改spec文件中analysis.datas如下:

a = Analysis(...
     datas= [ ('nlptest/data/stopwordsFile.txt', 'data/stopwordsFile.txt' ) ],

...

)

datas内部元组参数解释:

  • 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.

或者在a = Analysis()下面加上代码,告诉pyinstaller打包python文件时也将数据文件加入进去:
这个数据结构是TOC结构,类似数组列表a TOC object contains a list of tuples of the form (name,path,typecode)

a.datas+= [('stopwordsFile.txt', r'nlptest\stopwordsFile.txt', 'DATA'),]

a.datas += [('data/patterns.txt', 'TargetOpinion/Algorithm/data/patterns.txt',  'DATA'),
('data/English_stopwords.txt', 'TargetOpinion/Algorithm/data/English_stopwords.txt',  'DATA'),]

Note:第一个参数代码exe文件释放时候数据文件在temp/_mei***目录下的目录位置(也就是python代码中读取文件时候的位置(python代码中(python项目顶层目录为e/mine/py/nlp/时)e/mine/py/nlp/target/a.txt在exe释放时就成了C:\Users\...\AppData\Local\Temp\_MEI***\nlp/target/a.txt)),第二个参数代表要读取的数据文件的真实目录(没打包前的目录,spec文件相对路径?或者绝对路径),最后一个代表文件类型为数据文件。

typecode description name path
'DATA' Arbitrary files. Run-time name. Full path name in build.
'BINARY' A shared library. Run-time name. Full path name in build.
'EXTENSION' A binary extension to Python. Run-time name. Full path name in build.
'OPTION' A Python run-time option. Option code ignored.

[http://pythonhosted.org/PyInstaller/#the-toc-and-tree-classes]

当然也可以用tree数据结构读取目录下的所有文件,再将tree结构转换成toc结构:

a.datas += Tree('TargetOpinion/Algorithm/data/', prefix='data', excludes=[''], typecode='DATA')

这个等价于a.datas += [('data/patterns.txt', 'TargetOpinion/Algorithm/data/patterns.txt',  'DATA'), ('data/English_stopwords.txt', 'TargetOpinion/Algorithm/data/English_stopwords.txt',  'DATA'),]

Note: Tree(root, prefix=run-time-folder, excludes=string_list, typecode=code | 'DATA' )

参数root代表python代码中读取文件位置(没打包前的目录,spec文件相对路径?或者绝对路径),参数prefix代表运行时exe文件释放目录temp/_mei***下的相对子目录,参数excludes代表目录下要排除的文件如"*.pyc",typecode代表文件类型为数据文件。

[ http://pythonhosted.org/PyInstaller/#the-tree-class]

3. 再通过spec文件生成单文件exe文件:

pyinstaller -F E:/mine/python_workspace/test0/testMain.spec

或者

from PyInstaller.__main__ import runif __name__ =='__main__':opts =['TargetOpinionMain.spec', '-F']run(opts)

[Bundling data files with PyInstaller (--onefile)]

[http://pythonhosted.org/PyInstaller/#adding-data-files]

方案3:

使用python自带包pakutil

testMain.py

import nlptest

nlptest1.py

pkgutil.get_data('nlptest', patternFile)

但是这个和open打开是一样的,转换成exe后还是会找不到文件,并且如果不在testMain.py中添加import nlptest,get_data返回值为None。

另外要注意的问题

with open("***.txt", encoding='utf-8')as f

txt文件所在目录对应的是这个代码执行的目录(可能被另一个目录中的文件调用,则目录就是那个文件所在目录),而不是当前所在的文件a.py所在的目录。

[Python文件输入输出]

皮皮blog

错误2:pag_resources.distributionnotfound: pyinstaller testMain.py returned -1

在文件nlptest1.py中加入这一行出错

from PyInstaller.building.build_main import Analysis

就是引入PyInstaller出错,也不知道为什么,不加入就可以了,我的加入只是测试一个东西。

from:http://blog.csdn.net/pipisorry/article/details/50620495

ref:

pyinstaller相关错误相关推荐

  1. Scrapy运行中常见网络相关错误

    错误类型 错误名称 defer.TimeoutError 当延迟超时时,默认情况下会引发此错误(链接) TimeoutError 用户超时导致连接失败 DNSLookupError DNS查找失败 C ...

  2. 常见的 ChatGPT 相关错误提示及解决办法

    我汇总了一些大家在使用 ChatGPT 过程中,可能会遇到的一些问题以及相关错误提示,大家可以根据遇到的情况查看解决办法. 注册登陆问题: 错误提示:Too many signups from the ...

  3. Power BI中配置Python运行环境,及相关错误问题解决

    Power BI Desktop中支持python,在Power BI的数据获取.数据转换.数据可视化.数据输出的全流程中,都可以支持使用Python.关于如何全流程使用Python,可以参见文章ht ...

  4. pyinstaller 打包错误解决

    盘点在打包python文件成exe并运行过程中,遇到的问题: 1,打包出错, FileNotFoundError: ........lib\\site-packages\\pyyaml-5.3.1 - ...

  5. libQtCore.so.4相关错误

    此前由于ubuntu系统自带的QT版本与caffe的有冲突,我在管理时误删了ubuntu自带的qt4的相关组建,如QtCore等. 此后,每次打开基于qt4的程序时都会报如下错误: ImportErr ...

  6. 解决麒麟系统arm环境无法安装pyinstaller的错误:Checking for library z : not found

    错误信息如下: [root@ecs-6af3 ~]# pip3 install pyinstaller==4.0 WARNING: Running pip install with root priv ...

  7. Android Studio构建时报gradle相关错误的解决办法

    坑1:Connection timed out: connect. If you are behind an HTTP proxy, please configure the proxy settin ...

  8. vc编译器 msvcr.dll、msvcp.dll的含义和相关错误的处理

    转自:http://blog.csdn.net/sptoor/article/details/6203376 很久没有写程式设计入门知识的相关文章了,这篇文章要来谈谈程式库 (Library) 连结, ...

  9. spring boot 整合 jetcache 相关错误

    版本: jdk1.8 spring boot 2.2.5.RELEASE jetcache-starter-redis 2.6.0 spring boot 版本升级到2.2.2 以上版本,jetcac ...

  10. python生成exe,pyinstaller编码错误或闪退,果断换坑cxfreeze!

    pyinstaller的大坑 最近需要将一个python的Gui程序打包为exe 按照网上博客的建议--"py2exe很久没有更新,完全不能使用,应该换用pyinstaller", ...

最新文章

  1. ClientScriptManager.RegisterStartupScript.
  2. 基于SSM的餐饮工业化管理系统-计算机毕业设计
  3. openssl算法 —— 利用openssl进行BASE64编码解码、md5/sha1摘要、AES/DES3加密解密
  4. 虚拟打印机开发日志(一):使用x64 WIN7编译环境编译的完整步骤
  5. springioc注解版运行效果演示
  6. makefile 打印变量_[Makefile] 缩进与空格--记录踩过的坑
  7. 基于LVS对LAMP做负载均衡集群
  8. 用Mindjet MindManager 15 打开文件后停止响应的解决方法
  9. 《人工智能与模式识别》
  10. 介绍计算机硬件的英语作文,电脑各部分英文介绍
  11. 使用Eclipse搭建STM32嵌入式开发环境
  12. ISO7816协议中psam卡片的延时单元etu
  13. 人生于世上,有几个知己……
  14. selenium滑动验证
  15. Python爬取王者荣耀所有英雄以及高清大图
  16. 从现实世界的角度去理解计算机领域的知识
  17. 微信小程序 -- 图片模糊效果
  18. 【面试篇】牛客网面试总结
  19. fasterxml-jackson发生Can not deserialize instance of的原因
  20. 解决ThinkPad联想 笔记本电脑无法连接隐藏网络问题-提示“无法连接这个网络”

热门文章

  1. 设计模式那点事读书笔记(2)----抽象工厂模式
  2. linux软链接和硬链接的区别
  3. ZeroMQ 的模式
  4. c#关于委托和事件(二)(介绍的很详细)
  5. 性能测试的那些事儿!
  6. 使用libevhtp编写HTTP服务器的方法
  7. 网页布局02 盒子模型
  8. 刷题总结——蜥蜴(ssoj网络流)
  9. 浏览器Html 5兼容性测试
  10. pdf2image安装