不多说了,直接上代码记录:
#!/usr/bin/lgy
#-*-coding:utf-8-*-
import urllib2,threading
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from push_progress import *
from time import time
# 暂时没用到 多线程任务下载用到
lock = threading.RLock()
class UpdateWidget(QWidget):
def __init__(self,parent=None):
super(UpdateWidget,self).__init__(parent)
self.url = ""
self.buffer = 10000
self.start_size = 0
self.end_size = 0
self.fobj=""
self.progress=QProgressBar()
self.connect(self,SIGNAL("Getproess(float)"),self.ceshi2)
self.size_layout=QHBoxLayout()
self.sizetotal=QLabel()
self.connect(self,SIGNAL("Getsizetotal(int)"),self.ceshi3) #接收
self.sizenow=QLabel()
self.connect(self,SIGNAL("Getsizenow(int)"),self.ceshi4)
self.size_layout.addWidget(self.sizenow)
self.size_layout.addWidget(self.sizetotal)
self.size_layout.addStretch(1)
self.speedlabel=QLabel()
self.speedlabel.setText("50 kb/s")
self.connect(self,SIGNAL("Getspeed(float)"),self.ceshi)
self.main_layout=QVBoxLayout()
self.main_layout.addWidget(self.progress)
self.main_layout.addLayout(self.size_layout)
self.main_layout.addWidget(self.speedlabel)
self.setLayout(self.main_layout)
self.download()
self.resize(320,160)
def download(self):
url='http://down.360safe.com/se/360se7.3.0.146.exe'
t = threading.Thread(target=self.main,args=(url, 1, 'c:/360.exe',10000))
t.setDaemon(True)
t.start()
def ceshi(self,i):
speed=round(i,2)
#判断Mb,Kb
if speed>=1000:
mbspeed=round(speed/1000,2)
self.speedlabel.setText("{0} Mb/s".format(mbspeed))
else:
self.speedlabel.setText("{0} Kb/s".format(speed))
def ceshi2(self,i):
self.progress.setValue(round(i,2))
def ceshi3(self,i):
stol=round(float(i)/1024/1024,2)
self.sizetotal.setText("{0} M".format(stol))
def ceshi4(self,i):
stol=round(float(i)/1024/1024,2)
self.sizenow.setText("{0} M / ".format(stol))
def _download(self,url, totalsize,fobj, buffer):
start_time=time()
req = urllib2.Request(url)
f = urllib2.urlopen(req)
# 初始化当前文件位置偏移
offset = 0
while 1:
block = f.read(buffer)
# 当前线程数据获取完毕后则退出
if not block:
print u'完成退出循环'
break
#当前耗时
dural_time=float(time()) - float(start_time)
# 设置文件对象偏移地址
fobj.seek(offset)
# 写入获取到的数据
fobj.write(block)
offset = offset + len(block)
#计算下载速度
speed = (float(offset)/float(dural_time)/(1000*1000))*1000
#计算下载进度
proess=float(offset)/float(totalsize)*100
#print proess
self.emit(SIGNAL("Getsizenow(int)"),offset) #发送当前文件大小信号
self.emit(SIGNAL("Getproess(float)"),proess) #发送当前进度
self.emit(SIGNAL("Getspeed(float)"),speed) #发送当前下载速度
def main(self,url, thread=1, save_file='', buffer=1024):
# 获取文件的大小
req = urllib2.urlopen(url)
size = int(req.info().getheaders('Content-Length')[0])
self.emit(SIGNAL("Getsizetotal(int)"),size)
# 初始化文件对象
self.fobj = open(save_file, 'wb')
t = self._download(url, size ,self.fobj, buffer)
# 关闭文件对象
self.fobj.close()
print u'下载完成!'
if __name__=='__main__':
import sys
app=QApplication(sys.argv)
tree=UpdateWidget()
tree.show()
sys.exit(app.exec_())
后面的可自行拓展功能,效果如下:
下载360的速度有点快。。。。