python程序封装成exe_Python中.py文件打包成exe可执行文件详解

本文介绍如何使用PyQt5创建一个简单的图形用户界面(GUI),用于展示通过Python爬虫抓取的新浪新闻头条,并利用Pyinstaller将Python程序打包成独立的可执行文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

最近做了几个简单的爬虫python程序,于是就想做个窗口看看效果。

首先是,窗口的话,以前没怎么接触过,就先考虑用Qt制作简单的ui。这里用前面sinanews的爬虫脚本为例,制作一个获取当天sina头条新闻的窗口。

生成py文件后,运行该py文件,这里窗口我只是随便拖了几个组件进去,主要的text browser用于显示获取到的sinanews。

首先贴一下我的配置

官方下载:

PyQt5-5.2.1 for Py3.3(当安装完Python3.3后,安装对应PyQt,其会找到Python安装目录,不用更改安装目录)

本地下载:

PyQt5-5.2.1 for Py3.3(当安装完Python3.3后,安装对应PyQt,其会找到Python安装目录,不用更改安装目录)

Python3.3默认是没有安装pip的,需要下载get-pip.py运行之后,提示安装成功。

接下来就要安装一些必要的组件了。为了安装方便,先把pip添加进环境变量。

下面我们就可以用pip命令安装组件了。

先把sina_news.py贴出来,观察需要哪些组件。

1

2

3

4

5

6

7

8

9

10

11

12

import requests

from bs4import BeautifulSoup

res= requests.get('http://news.sina.com.cn/china/')

res.encoding= 'utf-8'

soup= BeautifulSoup(res.text,'html.parser')

for newsin 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)

发现import requests,import BeautifulSoup 所以先来安装这些组件

1

2

3

pip install requests

pip install BeautifulSoup4

当我们把这段代码贴进窗口代码后:

x.py

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

# -*- 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 PyQt5import QtCore, QtGui, QtWidgets

from bs4import 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 newsin 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_())

如果前面顺利的话,现在用python运行x.py应该能看到显示的窗口。

下面就是打包的过程了,这里笔者用的Pyinstaller,没有安装的话,要安装一下:

1

pip install pyinstaller

安装完成后,cmd路径cd到x.py所在目录。

打包命令:

1

Pyinstaller-w x.py

此时,在x.py便生成dist文件夹,打包的x.exe就在此文件夹下。双击x.exe显示效果:

1-20092509531O55.jpg

当然还有许多改进的地方,比如在上面选择日期,获得指定日期的头条新闻。

笔者在这片博文主要介绍py文件的打包过程。

可能遇到的问题:

打开打包后的程序无法运行显示:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

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

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

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

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

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

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

ImportError: No module named 'urllib3'

Failed to execute script test

当然这个错误代码,当时我没有保留,这是版本不匹配造成的:

我的Pyinstaller为3.2

需要降低requests的版本,requests2.10可以成功打包,而2.11就不行。这里贴上解决此问题用到的requests2.10不知道以后会不会修复这个问题。这个bug昨天做梦我还梦到呢。今天早上起来就解决了,兴奋的受不了。希望在此过程中遇到的问题对你会有所帮助。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对服务器之家的支持。

<think>我们使用pyinstaller打包Python代码为exe文件。步骤通常如下:1.安装pyinstaller2.在终端中运行打包命令3.可选地添加一些参数,比如指定图标、单文件打包等。详细步骤:1.确保已经安装了pyinstaller。如果没有,可以通过pip安装:pipinstallpyinstaller2.在VSCode中打开终端(Terminal),切换到需要打包Python文件所在目录。3.执行打包命令。例如,要打包main.py文件,可以使用:pyinstaller-F-w-iicon.icomain.py参数说明:-F,--onefile:打包一个单独的exe文件。-w,--windowed,--noconsole:运行时不显示命令行窗口(对于GUI程序适用,如果是命令行程序则不要使用这个参数)。-iicon.ico:设置程序的图标(可选,需要提前准备好ico格式的图标文件)。4.打包后,在项目目录下的dist文件夹中可以找到生exe文件。5.注意:如果程序依赖外部文件(如图片、配置文件等),则不能使用单文件模式(-F),因为这些文件不会被打包exe中。此时,可以使用不带-F的打包方式(默认是文件夹模式),然后将外部文件放在dist文件夹中的相应位置。6.对于文件夹模式(默认),pyinstaller会创建一个包含exe文件和所有依赖的文件夹。此时,如果需要分发,整个文件夹都要分发。7.如果遇到打包程序运行错误,可能是由于某些依赖没有被正确打包。可以使用以下命令查看详细打包过程:pyinstaller--debugall...或者不使用--debug,但查看生时的日志。8.也可以使用.spec文件进行高级配置(第一次运行pyinstaller后会自动生.spec文件,然后可以修改它并运行pyinstaller命令指定该spec文件重新打包)。常见问题:-打包文件过大:因为pyinstaller打包了整个Python解释器和依赖库。可以使用虚拟环境来减少不必要的库。-反病毒软件误报:这是常见问题,因为打包程序行为可能被怀疑。可以考虑对exe进行数字签名等。示例命令:pyinstaller--onefile--windowed--icon=myicon.icomyapp.py最后,在VSCode中,我们通常使用内置终端运行这些命令即可。注意:确保在打包前测试代码,并且最好在干净的虚拟环境中进行打包,以避免引入不必要的依赖。如果程序有数据文件,可以使用--add-data参数:pyinstaller--add-data"path/to/data;destination_folder"...其中,在Windows上路径分隔符用分号,在Linux和Mac上用冒号。例如,将当前目录下的images文件打包exe所在目录的images子文件夹中:pyinstaller--onefile--add-data"images;images"myapp.py另外,如果程序需要隐藏命令行窗口,使用-w;如果不需要(命令行程序)则不要使用-w。解释:使用pyinstaller打包时,它会分析你的Python脚本,找到脚本运行所需要的所有模块和库,然后将这些文件(包括Python解释器)打包到一个目录(或一个文件)中,这样就可以在没有Python环境的计算机上运行。§§相关问题§§:1.如何使用pyinstaller打包时添加数据文件?2.pyinstaller打包exe文件为什么很大?3.如何解决pyinstaller打包后运行出现“failedtoexecutescript”错误?4.pyinstaller打包如何隐藏命令行窗口?</think> 在VSCode中使用PyInstaller打包Python代码为可执行.exe文件的步骤如下: ### 完整操作步骤 1. **安装PyInstaller**(在VSCode终端中执行): ```bash pip install pyinstaller ``` 2. **创建示例Python文件**(以`main.py`为例): ```python # main.py 示例 def main(): print("Hello from exe!") input("Press Enter to exit...") if __name__ == "__main__": main() ``` 3. **生.exe文件**(在终端执行): ```bash pyinstaller --onefile --windowed --icon=app.ico main.py ``` - `--onefile`:生单个.exe文件 - `--windowed`:隐藏命令行窗口(GUI程序必选) - `--icon=app.ico`:自定义图标(需准备.ico文件) 4. **查找生文件**: 打包后,在项目目录的`dist/`文件夹中找到`.exe`文件 ### 参数详解 | 参数 | 作用 | |------|------| | `--onefile` | 生单一.exe文件 | | `--windowed` | 禁用命令行终端(适合GUI程序) | | `--noconsole` | 同`--windowed`(PyInstaller 4.0+) | | `--icon=app.ico` | 设置程序图标 | | `--name=AppName` | 设置输出文件名 | | `--add-data "src;dst"` | 添加资源文件(分号分隔源路径和目标路径) | ### 常见问题解决方案 1. **依赖缺失问题**: ```bash pyinstaller --hidden-import=missing_module main.py ``` 2. **生文件过大**: - 使用虚拟环境安装仅需依赖 ```bash python -m venv venv venv\Scripts\activate pip install only_required_packages ``` 3. **添加外部资源**: ```bash pyinstaller --add-data "images/*;images/" main.py ``` ### 代码中访问资源文件的正确方式 ```python import sys import os def resource_path(relative_path): """ 获取资源绝对路径 """ base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__))) return os.path.join(base_path, relative_path) # 使用示例 image_path = resource_path("images/logo.png") ``` ### 打包后执行错误排查 1. 用`--debug all`参数生调试版: ```bash pyinstaller --debug all main.py ``` 2. 测试模式检查依赖: ```bash pyinstaller --onefile main.py .\dist\main.exe ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值