700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > conda 创建虚拟环境 安装tensorflow PyQt5 绘制 GUI Pyinstaller 打包 .py 为 exe

conda 创建虚拟环境 安装tensorflow PyQt5 绘制 GUI Pyinstaller 打包 .py 为 exe

时间:2022-12-19 12:26:10

相关推荐

conda 创建虚拟环境 安装tensorflow PyQt5 绘制 GUI Pyinstaller 打包 .py 为 exe

文章目录

一、使用conda创建Python虚拟环境1. 常用conda命令2.命令效果展示二、安装tensorflow三、Pycharm配置对应环境四、补充安装项目所需包1. 安装PIL、tqdm2.(1)keras.xxx报错2.(2)tensorflow has no attribute 'Python'报错3.PyQt5安装4.Pycharm External Tools 配置5.tensorflow FutureWarning 解决五、PyQt5 绘制 GUI1.绘制技巧2.功能关联六、Pyinstaller 打包 .py 为 exe第一步:安装`Pyinstaller`第二步:使用`Pyinstaller` 总结

一、使用conda创建Python虚拟环境

1. 常用conda命令

conda info --env # 查看已有的虚拟环境conda activate xxx # 激活虚拟环境,xxx为虚拟环境名称conda deactivate xxx # 退出当前虚拟环境,退回到base环境conda list # 查看当前环境下安装了哪些包conda search xxx # 查找xxx包的版本信息conda create -n xxx python=3.6 # 创建指定Python版本为3.6的虚拟环境,xxx为虚拟环境名称conda remove -n xxx --all # 完全删除名为xxx的虚拟环境(可用于虚拟环境重命名)

注:创建虚拟环境时,一定要在base环境下输入conda create -n xxx python=3.6

2.命令效果展示

(1)查看已有的虚拟环境

# 查看已有的虚拟环境(base) C:\Users\dekan>conda info --env# conda environments:#base * D:\Python_Anaconda_Install_PathtensorflowD:\Python_Anaconda_Install_Path\envs\tensorflowtensorflow-1.15.2 D:\Python_Anaconda_Install_Path\envs\tensorflow-1.15.2tensorflow-1.7.0 D:\Python_Anaconda_Install_Path\envs\tensorflow-1.7.0

(2)激活虚拟环境,xxx为虚拟环境名称

(base) C:\Users\dekan>conda activate tensorflow(tensorflow) C:\Users\dekan>

(3)退出当前虚拟环境,退回到base环境

(tensorflow) C:\Users\dekan>conda deactivate(base) C:\Users\dekan>

(4)查看当前环境下安装了哪些包

(base) C:\Users\dekan>conda list# packages in environment at D:\Python_Anaconda_Install_Path:## NameVersion Build Channel_anaconda_depends .10 py37_0 https://mirrors./anaconda/pkgs/main_ipyw_jlab_nb_ext_conf 0.1.0py37_0 defaultsalabaster 0.7.11 py37_0 defaultsaltgraph 0.17 pypi_0 pypianaconda custom py37_1 https://mirrors./anaconda/pkgs/main...... # 中间省略居多内容,全都是python包...zope 1.0 py37_1 defaultszope.interface 4.5.0 py37hfa6e2cd_0 defaultszstd 1.3.7h508b16e_0 https://mirrors./anaconda/pkgs/main

(5)查找xxx包的版本信息

(base) C:\Users\dekan>conda search tensorflowLoading channels: done# Name Version Build Channeltensorflow0.12.1py35_1 anaconda/cloud/conda-forgetensorflow0.12.1py35_2 anaconda/cloud/conda-forge......# 中间省略巨多内容,全都是tensorflow的各个版本信息...tensorflow 2.1.0 mkl_py37ha977152_0 anaconda/pkgs/maintensorflow 2.1.0 mkl_py37ha977152_0 pkgs/main

(6)创建Python版本为3.6的虚拟环境,xxx为虚拟环境名称

(base) C:\Users\dekan>conda create -n text_detector python=3.6Collecting package metadata (repodata.json): doneSolving environment: |## Package Plan ##environment location: D:\Python_Anaconda_Install_Path\envs\text_detectoradded / updated specs:- python=3.6The following packages will be downloaded:package| build---------------------------|-----------------pip-20.2.3 | py36_0 2.1 MB https://mirrors./anaconda/pkgs/mainpython-3.6.12 | h5500b2f_2 17.8 MB https://mirrors./anaconda/pkgs/mainsetuptools-49.6.0| py36_1 957 KB https://mirrors./anaconda/pkgs/main------------------------------------------------------------Total: 20.8 MBThe following NEW packages will be INSTALLED:certifi anaconda/pkgs/main/win-64::certifi-.6.20-py36_0pipanaconda/pkgs/main/win-64::pip-20.2.3-py36_0python anaconda/pkgs/main/win-64::python-3.6.12-h5500b2f_2setuptools anaconda/pkgs/main/win-64::setuptools-49.6.0-py36_1sqlite anaconda/pkgs/main/win-64::sqlite-3.33.0-h2a8f88b_0vc anaconda/pkgs/main/win-64::vc-14.1-h0510ff6_4vs_runtimeanaconda/pkgs/main/win-64::vs_runtime-14.16.27012-hf0eaf9b_3wheel anaconda/pkgs/main/noarch::wheel-0.35.1-py_0wincertstore anaconda/pkgs/main/win-64::wincertstore-0.2-py36h7fe50ca_0zlibanaconda/pkgs/main/win-64::zlib-1.2.11-h62dcd97_4Proceed ([y]/n)

当然是选择原谅,呸,当然是选择y,下载过程结束后,Anaconda Prompt 显示:

done## To activate this environment, use##$ conda activate text_detector## To deactivate an active environment, use##$ conda deactivate

激活新创建的虚拟环境,开始愉快的安装tensorflow

(7)虚拟环境重命名

Anaconda中并无具体的重命名命令,所谓的“重命名”是指先复制原虚拟环境,再删除。

如名为“zhizunbao”的虚拟环境,我们想将其重命名为"zixiaxianzi",可进行如下操作:

conda create -n zixiaxianzi --clone zhizunbao # 使用 clone 命令,将名为'zhizunbao'的虚拟环境,“克隆”为名为'zixiaxianzi'的虚拟环境conda remove -n zhizunbao --all# “克隆”过程结束后,将原虚拟环境连根拔起,彻底删除!

二、安装tensorflow

1.激活虚拟环境

base环境下输入conda activate text_detector,其中text_detector为新创建的环境名称,视具体情况而定。我是为文本检测任务而创建的虚拟环境,故命名为此。

2.安装适合自己项目的tensorflow版本

(base) C:\Users\dekan>conda activate text_detector(text_detector) C:\Users\dekan>conda install tensorflow==1.14.0Collecting package metadata (repodata.json): doneSolving environment: \## Package Plan ##environment location: D:\Python_Anaconda_Install_Path\envs\text_detectoradded / updated specs:- tensorflow==1.14.0The following packages will be downloaded:package| build---------------------------|-----------------absl-py-0.10.0 | py36_0 169 KB https://mirrors./anaconda/pkgs/mainmkl_fft-1.2.0 | py36h45dec08_0 135 KB https://mirrors./anaconda/pkgs/mainprotobuf-3.13.0 | py36h33f27b4_1 610 KB https://mirrors./anaconda/pkgs/maintensorboard-1.14.0 | py36he3c9ec2_0 3.3 MB https://mirrors./anaconda/pkgs/maintensorflow-1.14.0|eigen_py36hf4fd08c_0 4 KB https://mirrors./anaconda/pkgs/maintensorflow-base-1.14.0|eigen_py36hdbc3f0e_0 52.4 MB https://mirrors./anaconda/pkgs/main------------------------------------------------------------Total: 56.6 MBThe following NEW packages will be INSTALLED:_tflow_selectanaconda/pkgs/main/win-64::_tflow_select-2.2.0-eigenabsl-py anaconda/pkgs/main/win-64::absl-py-0.10.0-py36_0astor anaconda/pkgs/main/win-64::astor-0.8.1-py36_0blasanaconda/pkgs/main/win-64::blas-1.0-mklca-certificates anaconda/pkgs/main/win-64::ca-certificates-.7.22-0gastanaconda/pkgs/main/noarch::gast-0.4.0-py_0grpcio anaconda/pkgs/main/win-64::grpcio-1.31.0-py36he7da953_0h5pyanaconda/pkgs/main/win-64::h5py-2.10.0-py36h5e291fa_0hdf5anaconda/pkgs/main/win-64::hdf5-1.10.4-h7ebc959_0icc_rt anaconda/pkgs/main/win-64::icc_rt-.0.0-h0cc432a_1importlib-metadata anaconda/pkgs/main/win-64::importlib-metadata-1.7.0-py36_0intel-openmp anaconda/pkgs/main/win-64::intel-openmp-.2-254keras-applications anaconda/pkgs/main/noarch::keras-applications-1.0.8-py_1keras-preprocessi~ anaconda/pkgs/main/noarch::keras-preprocessing-1.1.0-py_1libprotobuf anaconda/pkgs/main/win-64::libprotobuf-3.13.0-h200bbdf_0markdown anaconda/pkgs/main/win-64::markdown-3.2.2-py36_0mklanaconda/pkgs/main/win-64::mkl-.2-256mkl-service anaconda/pkgs/main/win-64::mkl-service-2.3.0-py36hb782905_0mkl_fft anaconda/pkgs/main/win-64::mkl_fft-1.2.0-py36h45dec08_0mkl_random anaconda/pkgs/main/win-64::mkl_random-1.1.1-py36h47e9c7a_0numpy anaconda/pkgs/main/win-64::numpy-1.19.1-py36h5510c5b_0numpy-base anaconda/pkgs/main/win-64::numpy-base-1.19.1-py36ha3acd2a_0openssl anaconda/pkgs/main/win-64::openssl-1.1.1h-he774522_0protobuf anaconda/pkgs/main/win-64::protobuf-3.13.0-py36h33f27b4_1pyreadline anaconda/pkgs/main/win-64::pyreadline-2.1-py36_1scipy anaconda/pkgs/main/win-64::scipy-1.5.2-py36h9439919_0sixanaconda/pkgs/main/noarch::six-1.15.0-py_0tensorboard anaconda/pkgs/main/win-64::tensorboard-1.14.0-py36he3c9ec2_0tensorflow anaconda/pkgs/main/win-64::tensorflow-1.14.0-eigen_py36hf4fd08c_0tensorflow-base anaconda/pkgs/main/win-64::tensorflow-base-1.14.0-eigen_py36hdbc3f0e_0tensorflow-estima~ anaconda/pkgs/main/noarch::tensorflow-estimator-1.14.0-py_0termcoloranaconda/pkgs/main/win-64::termcolor-1.1.0-py36_1werkzeug anaconda/pkgs/main/noarch::werkzeug-1.0.1-py_0wrapt anaconda/pkgs/main/win-64::wrapt-1.12.1-py36he774522_1zippanaconda/pkgs/main/noarch::zipp-3.1.0-py_0Proceed ([y]/n)?

当然是再一次选择原谅,呸,再一次选择y,等待下载安装完成。这就涉及到conda配置镜像源的问题了,请参考。

三、Pycharm配置对应环境

创建虚拟环境后,还需对Pycharm进行简单配置,以使当前项目的Project Interpreter为特地为其创建的虚拟环境。

流水线:File→Settings→Project:xxxx→Project Interpreter→▼→show all

流水线:➕→Existing environment→...(选择路径)→🆗

注1:选择路径为新创建的虚拟环境路径,因每人Anaconda安装路径不同,故路径前半部分不尽相同。后半部分一般为:envs→text_detector→python.exe

注2:第四步选择🆗后,直接一路🆗带闪电!!!

四、补充安装项目所需包

1. 安装PIL、tqdm

conda install pillowconda install tqdm

注1:PIL包仅支持到Python 2.7,Python 3.6下PIL包对应的安装名称为pillow

注2:tqdm为Python进度条包,在需要进度条显示的程序中应用很普遍,常规安装

2.(1)keras.xxx报错

(a): from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping(b): from tensorflow.python.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, TensorBoard, EarlyStopping

注:安装完tensorflow后,keras是集成一起安装的,当使用上述(a)语句可能会报错,修改为(b)语句即可。

2.(2)tensorflow has no attribute 'Python’报错

根据2.(1)修改完keras.xxx报错后,可能会出现2.(2)的错误,这个错误一般出现在import tensorflow.python.keras.xxx as xxx中,在stack overflow 中也有提到类似的错误,引用以为大佬的解答:

@MrTsjolder: the import succeeds without AttributeError because the package exists. Why should it fail? The thing is that when import tensorflow.python is executed, tensorflow is imported first, before tensorflow.python. tensorflow.init.py explicitly imports what it wants from tensorflow.python then deletes the reference to python so it is not in the namespace of the importing code. Because tensorflow.python was already imported, it is not imported again, so the deleted reference remains deleted. – mhawke Nov 16 '17 at 0:02

按照大神的解释,import tensorflow.python.keras.xxx as xxx这种类型的语句,它的执行顺序为,先执行import tensorflow,执行完这一条后,其实tensorflow.python已经被导入了,然后tensorflow.__init__() explicitly deletes its reference to the tensorflow.python module(tensorflow.init() 删除了对于tensorflow.python的引用),以此保证同一个module不会导入两次。

因此,仅仅想导入tensorflow.python.keras.xxx,可以使用from tensorflow.python.keras import xxx

3.PyQt5安装

项目需要使用PyQt5绘制GUI界面,安装这家伙的时候踩过不少坑。总而言之一句话:conda install PyQt5是安装不上这个包包的!!!

参考了博文“PyQt5+Pycharm安装和配置”果断回归自然,使用pip install PyQt5 -i /simple,安装成功。

(text_detector) C:\Users\dekan>pip install PyQt5 -i /simpleLooking in indexes: /simpleCollecting PyQt5Downloading /packages/44/b3/4402c5571e69bcc4e54a6f5948c1d6b7a37718acb414b42f593764ec3918/PyQt5-5.15.1-5.15.1-cp35.cp36.cp37.cp38.cp39-none-win_amd64.whl (59.4 MB)|████████████████████████████████| 59.4 MB 63 kB/sCollecting PyQt5-sip<13,>=12.8Downloading /packages/59/0e/f51483e98c407687ec6e99d21ec1333c42a4d285933f2863494676d22896/PyQt5_sip-12.8.1-cp36-cp36m-win_amd64.whl (62 kB)|████████████████████████████████| 62 kB 384 kB/sInstalling collected packages: PyQt5-sip, PyQt5Successfully installed PyQt5-5.15.1 PyQt5-sip-12.8.1

除了安装PyQt5外,还需要安装pip install PyQt5-tools -i /simple

(text_detector) C:\Users\dekan>pip install PyQt5-tools -i /simpleLooking in indexes: /simpleCollecting PyQt5-toolsDownloading /packages/96/f3/b82435b858f3cae6c1f85c0230f476e9250bafb89c6a594e12fbde3018d5/pyqt5_tools-5.15.1.1.7.4-cp36-cp36m-win_amd64.whl (57.5 MB)|████████████████████████████████| 57.5 MB 1.3 MB/sCollecting clickDownloading /packages/d2/3d/fa76db83bf75c4f8d338c2fd15c8d33fdd7ad23a9b5e57eb6c5de26b430e/click-7.1.2-py2.py3-none-any.whl (82 kB)|████████████████████████████████| 82 kB 3.0 MB/sCollecting python-dotenvDownloading /packages/f2/16/28d434b28c5be29a6af8fd0e3a2bda3bd30500ef0cd17bc79f7a6793a8d4/python_dotenv-0.14.0-py2.py3-none-any.whl (17 kB)Requirement already satisfied: pyqt5==5.15.1 in d:\python_anaconda_install_path\envs\text_detector\lib\site-packages (from PyQt5-tools) (5.15.1)Requirement already satisfied: PyQt5-sip<13,>=12.8 in d:\python_anaconda_install_path\envs\text_detector\lib\site-packages (from pyqt5==5.15.1->PyQt5-tools) (12.8.1)Installing collected packages: click, python-dotenv, PyQt5-toolsSuccessfully installed PyQt5-tools-5.15.1.1.7.4 click-7.1.2 python-dotenv-0.14.0

又是一路火花带闪电,蹭蹭蹭蹭安装完!!!

4.Pycharm External Tools 配置

为了能够使用PyQt5进行GUI界面的制作,安装Package后还需在Pycharm中进行简单配置,老规矩,流水线:File→Settings→Tools→External Tools,具体操作可参考博客。

提一下配置过程中,几个路径的选择:

(1)Qt_Designer:

Program: D:\Python_Anaconda_Install_Path\Lib\site-packages\pyqt5_tools\Qt\bin\designer.exe

具体为Anaconda安装路径中,site-packages文件下的designer.exe

Working directory:D:\Python_Anaconda_Install_Path\Lib\site-packages\pyqt5_tools\Qt\bin

具体为Anaconda安装路径中,site-packages文件下的

(2)PyUIC,该工具的作用在于将.ui文件转化为.py文件

Program:D:\Python_Anaconda_Install_Path\Scripts\pyuic5.exe

具体为Anaconda安装路径中Scripts文件夹下的pyuic5.exe

Working directory:E:\Postgraduate\Ui_ship_plate_recognition_exe_version\UI

具体为实际工程目录下的保存.ui文件的文件夹

流水线:Tools→External Tools→Qt_Designer,启动PyQt5,可以看到,PyQt5界面,与Qt界面并无二异

5.tensorflow FutureWarning 解决

即使是对于没有强迫症的我来说,每次跑程序看到一堆红红的waring,还是不怎么舒服。因为装的Tensorflow版本为1.14.0,算是比较老的版本了,因此出现了不少FutureWarning,数量不少,类型统一。

FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.np_resource = np.dtype([("resource", np.ubyte, 1)])

都长这个🦆,点击warning跳转到对应的语句,修改方法如下:将1 替换为 (1,) 即可

np_resource = np.dtype([("resource", np.ubyte, (1,))])

把所有该类型的warning做如此处理,就完事了!!!

五、PyQt5 绘制 GUI

具体绘制方法不再赘述,这里只记录一些遇到的问题。

1.绘制技巧

使用Qt_designer绘制GUI界面时,可通过Ctrl+R查看界面;

绘制完成后,使用Py_UIC将.ui文件转化为同名的.py文件,在该文件末尾加上如下代码,即可查看设计好的GUI界面:

if __name__ == "__main__":import sysapp = QtWidgets.QApplication(sys.argv)widget = QtWidgets.QMainWindow()ui = Ui_MainWindow()ui.setupUi(widget)widget.show()sys.exit(app.exec_())

2.功能关联

GUI界面中button对应着不同的功能,需要在工程目录下编码将button与对应的function进行clicked连接

self.Open_File.clicked.connect(self.openFile)self.Recognition.clicked.connect(self.predict_results)self.manual_locate.clicked.connect(self.manual_locate_function)self.object_choose.clicked.connect(self.object_choose_function)self.img_zoom_in.clicked.connect(self.img_zoom_in_function)self.img_zoom_out.clicked.connect(self.img_zoom_out_function)

Ui_MainWindow类中的retranslateUi()函数中添加clicked.connect关系。

六、Pyinstaller 打包 .py 为 exe

更新时间:.10.12,回来填坑

Pyinstall正逐渐成为将Python程序打包为exe的首选,但具体使用时还有很多值得注意的细节。

第一步:安装Pyinstaller

工欲善其事,必先利其器。激活项目代码所在的虚拟环境,使用pip install pyinstaller -i /simple,借助镜像源安装,很快大功告成:

Successfully built pyinstaller pefile futureInstalling collected packages: pyinstaller-hooks-contrib, pywin32-ctypes, future, pefile, altgraph, pyinstallerSuccessfully installed altgraph-0.17 future-0.18.2 pefile-.4.18 pyinstaller-4.0 pyinstaller-hooks-contrib-.9 pywin32-ctypes-0.2.0

第二步:使用Pyinstaller

使用Pyinstaller,打包Python程序,步骤如下:

进入待打包的程序所在文件

打开Anaconda Prompt,输入cd /d E:\xxx\exe_version,对待打包程序右键→属性,复制“位置”处的路径,粘贴到cd /d后面即可。

根据Pyinstall参数说明,键入命令进行打包

一切为了简单,只列举常用的几个参数:

键入命令

(text_detector) E:\xxx\exe_version>pyinstaller -c -D Ui_drawing.py -p predict_function_Ui首次对程序进行打包,尤其是存在GUI界面和外部依赖的程序,压根不可能一次性成功。

因此,命令我们选择:

-c显示命令行窗口,用来查看错误提示

-D生成目录性结果,可以提高exe打开速度

-p主程序入口外,添加额外的.py文件

查看Pyinstaller生成结果

键入命令,运行完成后,会在主程序入口文件夹下生成三个新的文件:build、dist、xxx.spec,前二者为文件夹,使用记事本打开.spec文件(这哥们很重要,后面的步骤都要靠它了)。build文件,后续可删;dist文件保存exe及依赖

运行exe,命令行窗口截图查看报错

在dist文件中找到Ui_drawing这是打包好的exe文件,双击运行。首次打开会长时间停留在命令行界面,一般不会一次性运行成功。所以要在命令行窗口显示信息,并且迅速消失前,截图保留下错误提示。

PS:我这图,截了8次!!!!

主要最后一句:No such file or directory,程序运行所需要的外部依赖没有加载成功,导致程序运行失败。这是当程序存在如.txt、.hdf5、.h5等后缀的文本文件、模型等外部依赖时的一类错误。使用.spec文件进行修正。

修正!!!

需要修改两处地方,解决该类错误:

(1)修改源程序中的文件读取代码,从exe为加载依赖而创建的临时文件夹中读取所需要的依赖。

(2)在.spec中添加datas = [] 信息

在需要读取外部依赖的源程序中,添加如下代码:

def resource_path(relative_path):"""获取文件资源的绝对路径"""try:# Pyinstaller 创建临时文件夹,将路径存储于_MEIPASSbase_path = sys._MEIPASSexcept Exception:base_path = os.path.abspath('.')return os.path.join(base_path, relative_path)

即读取Pyinstaller创建的临时文件夹目录,以依赖的相对路径为输入,返回依赖的绝对路径。

以俺拼手速截图下来的错误来讲,因为缺少.txt依赖,所以运行失败。因此必须通过resource_path()函数获取文件路径,代码如下:

char_file = resource_path('res/char_std_5990.txt')

然后修改.spec文件,万事俱备前的那股东风。

找到datas = [],使用它对exe添加外部资源文件。这是个list,里面的元素为tuple,因此格式为datas = [(A, B), (C, D)]其中A,C为依赖的相对路径,B、D为依赖所在的文件夹。

我自个的修改内容:

涉及到点点项目内容,码了吧。

东风以来,再次打包

作为上述修改后,重新打包exe,此时就要靠着.spec文件进行打包了,参数很简单。

Anaconda Prompt→cd /d→输入命令

pyinstaller -D Ui_drawing.spec

等待结束。。。。。。。。。

因为没有删除掉上一次生成的结果目录,所以命令行窗口很贴心的提示了我这个:

WARNING: The output directory "E:\Postgraduate\Ui_ship_plate_recognition_exe_version\dist\Ui_drawing" and ALL ITS CONTENTS will be REMOVED! Continue? (y/N)

老规矩,当然是选择原谅,呸,当然是选择"y"!!!

大功告成

放图撒花!!!

不忍直视的识别结果还是打个码吧。

此时我们打包好的exe运行时,是会出现命令行窗口的,因此在测试确定可以正常运行后,还需重新打包一次,此时需要修改.spec中的console=True修改为console=False,表示exe运行时关闭命令行窗口。然后键入:

pyinstaller -D Ui_drawing.spec

等待结束。。。。。。。。。

对了,再补一句,生成的build文件在exe程序在其他电脑上运行时,可直接删除。

总结

Pyinstaller打包好的程序还存在着体积过大的问题,网上的方案大多为新建虚拟环境,只安装用得到的python包,这是个解决方法。

还有个笨方法就是,在生成的exe文件夹中,一个个删除掉比较大的文件或文件夹,查看程序是否仍然能够正常运行。

exe层面的问题解决了,后面的算法还有点问题,唉。。。。

写Bug去了!!!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。