search
HomeBackend DevelopmentPython TutorialDetailed explanation of the example code for packaging .py files into exe executable files in Python

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)

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

pip install requests

pip install BeautifulSoup4

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_())

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

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

Packaging command:

Pyinstaller -w x.py

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>
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!

Statement
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
How do you append elements to a Python list?How do you append elements to a Python list?May 04, 2025 am 12:17 AM

ToappendelementstoaPythonlist,usetheappend()methodforsingleelements,extend()formultipleelements,andinsert()forspecificpositions.1)Useappend()foraddingoneelementattheend.2)Useextend()toaddmultipleelementsefficiently.3)Useinsert()toaddanelementataspeci

How do you create a Python list? Give an example.How do you create a Python list? Give an example.May 04, 2025 am 12:16 AM

TocreateaPythonlist,usesquarebrackets[]andseparateitemswithcommas.1)Listsaredynamicandcanholdmixeddatatypes.2)Useappend(),remove(),andslicingformanipulation.3)Listcomprehensionsareefficientforcreatinglists.4)Becautiouswithlistreferences;usecopy()orsl

Discuss real-world use cases where efficient storage and processing of numerical data are critical.Discuss real-world use cases where efficient storage and processing of numerical data are critical.May 04, 2025 am 12:11 AM

In the fields of finance, scientific research, medical care and AI, it is crucial to efficiently store and process numerical data. 1) In finance, using memory mapped files and NumPy libraries can significantly improve data processing speed. 2) In the field of scientific research, HDF5 files are optimized for data storage and retrieval. 3) In medical care, database optimization technologies such as indexing and partitioning improve data query performance. 4) In AI, data sharding and distributed training accelerate model training. System performance and scalability can be significantly improved by choosing the right tools and technologies and weighing trade-offs between storage and processing speeds.

How do you create a Python array? Give an example.How do you create a Python array? Give an example.May 04, 2025 am 12:10 AM

Pythonarraysarecreatedusingthearraymodule,notbuilt-inlikelists.1)Importthearraymodule.2)Specifythetypecode,e.g.,'i'forintegers.3)Initializewithvalues.Arraysofferbettermemoryefficiencyforhomogeneousdatabutlessflexibilitythanlists.

What are some alternatives to using a shebang line to specify the Python interpreter?What are some alternatives to using a shebang line to specify the Python interpreter?May 04, 2025 am 12:07 AM

In addition to the shebang line, there are many ways to specify a Python interpreter: 1. Use python commands directly from the command line; 2. Use batch files or shell scripts; 3. Use build tools such as Make or CMake; 4. Use task runners such as Invoke. Each method has its advantages and disadvantages, and it is important to choose the method that suits the needs of the project.

How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?How does the choice between lists and arrays impact the overall performance of a Python application dealing with large datasets?May 03, 2025 am 12:11 AM

ForhandlinglargedatasetsinPython,useNumPyarraysforbetterperformance.1)NumPyarraysarememory-efficientandfasterfornumericaloperations.2)Avoidunnecessarytypeconversions.3)Leveragevectorizationforreducedtimecomplexity.4)Managememoryusagewithefficientdata

Explain how memory is allocated for lists versus arrays in Python.Explain how memory is allocated for lists versus arrays in Python.May 03, 2025 am 12:10 AM

InPython,listsusedynamicmemoryallocationwithover-allocation,whileNumPyarraysallocatefixedmemory.1)Listsallocatemorememorythanneededinitially,resizingwhennecessary.2)NumPyarraysallocateexactmemoryforelements,offeringpredictableusagebutlessflexibility.

How do you specify the data type of elements in a Python array?How do you specify the data type of elements in a Python array?May 03, 2025 am 12:06 AM

InPython, YouCansSpectHedatatYPeyFeLeMeReModelerErnSpAnT.1) UsenPyNeRnRump.1) UsenPyNeRp.DLOATP.PLOATM64, Formor PrecisconTrolatatypes.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor