Home > Backend Development > Python Tutorial > Detailed explanation of the example code for packaging .py files into exe executable files in Python

Detailed explanation of the example code for packaging .py files into exe executable files in Python

高洛峰
Release: 2017-03-24 16:30:23
Original
3185 people have browsed it

This article mainly introduces you to the relevant information on packaging .py files into exe executable files in Python. The introduction in the article is very detailed. I believe it has certain reference value for everyone. Friends who need it can read it together. Take a look.

Preface

I recently made a few simple crawler python programs, so I wanted to make a window to see the effect.

First of all, as for windows, I haven’t had much contact with them before, so I will first consider using Qt to make a simple UI. Here we use the previous sinanews crawler script as an example to create a window to obtain the sina headlines of the day.

After generating the py file, run the py file. I just dragged a few components into the window here. The main text browser is used to display the obtained sinanews.

First post my configuration

Official download:

 PyQt5-5.2.1 for Py3.3 (after installing Python3.3, install the corresponding PyQt, which will find the Python installation directory without changing the installation directory)

Local download:

PyQt5-5.2.1 for Py3.3 (After installing Python3.3, install the corresponding PyQt, which will find the Python installation directory, no need to change the installation directory)

Python3.3 does not have pip installed by default. You need to download get-pip.py and run it. It will prompt that the installation is successful.

The next step is to install some necessary components. For ease of installation, first add pip to the environment variables.

Now we can use the pip command to install the component.

First post sina_news.py and observe what components are needed.

import requests
from bs4 import BeautifulSoup
res = requests.get('http://news.sina.com.cn/china/')
res.encoding = 'utf-8'
soup = BeautifulSoup(res.text,'html.parser')

for news in soup.select('.news-item'):
 if len(news.select('h2')) > 0:
 h2 = news.select('h2')[0].text
 a = news.select('a')[0]['href']
 time = news.select('.time')[0].text
 print(time,h2,a)
Copy after login

I found import requests, import BeautifulSoup, so let’s install these components first

pip install requests

pip install BeautifulSoup4
Copy after login

After we paste this code into the window code:

x.py

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'x.ui'
#
# Created by: PyQt5 UI code generator 5.8.1
#
# WARNING! All changes made in this file will be lost!
import sys
import requests
from PyQt5 import QtCore, QtGui, QtWidgets
from bs4 import BeautifulSoup

class Ui_x(object):
 def getNews():
 res = requests.get('http://news.sina.com.cn/china/')
 res.encoding = 'utf-8'
 soup = BeautifulSoup(res.text,'html.parser')
 title = []
 for news in soup.select('.news-item'):
 if len(news.select('h2')) > 0:
 h2 = news.select('h2')[0].text
 title.append(h2)
 a = news.select('a')[0]['href']
 time = news.select('.time')[0].text
 return '\n'.join(title)

 
 def setupUi(self, x):
 x.setObjectName("x")
 x.resize(841, 749)
 self.timeEdit = QtWidgets.QTimeEdit(x)
 self.timeEdit.setGeometry(QtCore.QRect(310, 10, 141, 31))
 self.timeEdit.setObjectName("timeEdit")
 self.dateEdit = QtWidgets.QDateEdit(x)
 self.dateEdit.setGeometry(QtCore.QRect(100, 10, 191, 31))
 self.dateEdit.setObjectName("dateEdit")
 self.textBrowser = QtWidgets.QTextBrowser(x)
 self.textBrowser.setGeometry(QtCore.QRect(60, 80, 701, 641))
 self.textBrowser.setObjectName("textBrowser")
 self.retranslateUi(x)
 QtCore.QMetaObject.connectSlotsByName(x)

 def retranslateUi(self, x):
 _translate = QtCore.QCoreApplication.translate
 x.setWindowTitle(_translate("x", "x"))

if __name__ == '__main__': 
 app = QtWidgets.QApplication(sys.argv)
 Form = QtWidgets.QWidget()
 ui = Ui_x()
 ui.setupUi(Form)
 Form.show()
 ui.textBrowser.setText(Ui_x.getNews())
 sys.exit(app.exec_())
Copy after login

If everything goes well, you should be able to see the displayed window when running x.py in python.

The following is the packaging process. The author uses Pyinstaller here. If it is not installed, you need to install it:

pip install pyinstaller
Copy after login

After the installation is completed, cd the cmd path to the directory where x.py is located.

Packaging command:

Pyinstaller -w x.py
Copy after login

At this time, the dist folder is generated in x.py, and the packaged x.exe is under this folder. Double-click x.exe to display the effect:

Detailed explanation of the example code for packaging .py files into exe executable files in Python

## Of course, there are many improvements, such as selecting a date above and getting the headlines on a specified date.

Possible problems:

The packaged program cannot be opened and it displays:

ImportError: No module named 'queue'

During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
 File "test.py", line 2, in <module>
 File "c:\users\hasee\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
 exec(bytecode, module.__dict__)
 File "site-packages\requests\__init__.py", line 63, in <module>
 File "c:\users\hasee\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
 exec(bytecode, module.__dict__)
 File "site-packages\requests\utils.py", line 24, in <module>
 File "c:\users\hasee\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
 exec(bytecode, module.__dict__)
 File "site-packages\requests\_internal_utils.py", line 11, in <module>
 File "c:\users\hasee\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
 exec(bytecode, module.__dict__)
 File "site-packages\requests\compat.py", line 11, in <module>
 File "c:\users\hasee\appdata\local\programs\python\python35-32\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 389, in load_module
 exec(bytecode, module.__dict__)
 File "site-packages\requests\packages\__init__.py", line 29, in <module>
ImportError: No module named 'urllib3'
Failed to execute script test</module></module></module></module></module></module>
Copy after login
Of course this error code , I did not retain it at the time. This was caused by a version mismatch:

My Pyinstaller is 3.2

The version of requests needs to be lowered, and requests2.10 can be packaged successfully. But 2.11 does not work. Posted here are the requests2.10 used to solve this problem. I don’t know if this problem will be fixed in the future. I was dreaming about this bug yesterday. I solved it when I woke up this morning. I was so excited that I couldn't stand it. I hope the questions you encounter during this process will be helpful to you.

The above is the detailed content of Detailed explanation of the example code for packaging .py files into exe executable files in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template