详解Python中.py文件打包成exe可执行文件实例代码

高洛峰
發布: 2017-03-24 16:30:23
原創
3114 人瀏覽過

這篇文章主要給大家介紹了在Python中.py檔打包成exe可執行檔的相關資料,文中介紹的非常詳細,相信對大家具有一定的參考價值,需要的朋友們下面來一起看看吧。

前言

最近做了幾個簡單的爬蟲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貼出來,觀察需要哪些元件。

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)
登入後複製
發現import requests,import BeautifulSoup 所以先來安裝這些元件

pip install requests

pip install BeautifulSoup4
登入後複製
當我們把這段程式碼貼進視窗程式碼後:

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_())
登入後複製
如果前面順利的話,現在用python運行x.py應該可以看到顯示的視窗。

下面就是打包的過程了,這裡筆者用的Pyinstaller,沒有安裝的話,要安裝一下:

pip install pyinstaller
登入後複製
安裝完成後,cmd路徑cd到x.py所在目錄。

打包指令:

Pyinstaller -w x.py
登入後複製
此時,在x.py便產生dist資料夾,打包的x.exe就在此資料夾下。雙擊x.exe顯示效果:

详解Python中.py文件打包成exe可执行文件实例代码

當然還有許多改進的地方,例如在上面選擇日期,獲得指定日期的頭條新聞。

可能遇到的問題:

打開打包後的程式無法執行顯示:

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>
登入後複製
當然這個錯誤代碼,當時我沒有保留,這是版本不匹配造成的:

我的Pyinstaller為3.2

需要降低requests的版本,requests2.10可以成功打包,而2.11就不行。這裡貼上解決此問題用到的requests2.10不知道以後會不會修復這個問題。這個bug昨天做夢我還夢到呢。今天早上起來就解決了,興奮的受不了。希望在過程中遇到的問題對你會有所幫助。

以上是详解Python中.py文件打包成exe可执行文件实例代码的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!