Python编写一个优美的下载器


Posted in Python onApril 15, 2018

本文实例为大家分享了Python编写下载器的具体代码,供大家参考,具体内容如下

#!/bin/python3 
# author: lidawei 
# create: 2016-07-11 
# version: 1.0 
# 功能说明: 
#  从指定的URL将文件取回本地 
##################################################### 
 
import http.client 
import os 
import threading 
import time 
import logging 
import unittest 
from queue import Queue 
from urllib.parse import urlparse 
 
logging.basicConfig(level = logging.DEBUG, 
     format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', 
     datefmt = '%a, %d %b %Y %H:%M:%S', 
     filename = 'Downloader_%s.log' % (time.strftime('%Y-%m-%d')), 
     filemode = 'a') 
 
class Downloader(object): 
 '''''文件下载器''' 
 url = '' 
 filename = '' 
 
 def __init__(self, full_url_str, filename): 
  '''''初始化''' 
  self.url = urlparse(full_url_str) 
  self.filename = filename 
 
 def download(self): 
  '''''执行下载,返回True或False''' 
  if self.url == '' or self.url == None or self.filename == '' or self.filename == None: 
   logging.error('Invalid parameter for Downloader') 
   return False 
 
  successed = False 
  conn = None 
  if self.url.scheme == 'https': 
   conn = http.client.HTTPSConnection(self.url.netloc) 
  else: 
   conn = http.client.HTTPConnection(self.url.netloc) 
  conn.request('GET', self.url.path) 
  response = conn.getresponse() 
  if response.status == 200: 
   total_size = response.getheader('Content-Length') 
   total_size = (int)(total_size) 
   if total_size > 0: 
    finished_size = 0 
    file = open(self.filename, 'wb') 
    if file: 
     progress = Progress() 
     progress.start() 
     while not response.closed: 
      buffers = response.read(1024) 
      file.write(buffers) 
 
      finished_size += len(buffers) 
      progress.update(finished_size, total_size) 
      if finished_size >= total_size: 
       break 
     # ... end while statment 
     file.close() 
     progress.stop() 
     progress.join() 
    else: 
     logging.error('Create local file %s failed' % (self.filename)) 
    # ... end if statment 
   else: 
    logging.error('Request file %s size failed' % (self.filename)) 
   # ... end if statment 
  else: 
   logging.error('HTTP/HTTPS request failed, status code:%d' % (response.status)) 
  # ... end if statment 
  conn.close() 
 
  return successed 
 # ... end download() method 
# ... end Downloader class 
 
class DataWriter(threading.Thread): 
 filename = '' 
 data_dict = {'offset' : 0, 'buffers_byte' : b''} 
 queue = Queue(128) 
 __stop = False 
 
 def __init__(self, filename): 
  self.filename = filename 
  threading.Thread.__init__(self) 
 
 #Override 
 def run(self): 
  while not self.__stop: 
   self.queue.get(True, 1) 
 
 def put_data(data_dict): 
  '''''将data_dict的数据放入队列,data_dict是一个字典,有两个元素:offset是偏移量,buffers_byte是二进制字节串''' 
  self.queue.put(data_dict) 
 
 def stop(self): 
  self.__stop = True 
 
class Progress(threading.Thread): 
 interval = 1 
 total_size = 0 
 finished_size = 0 
 old_size = 0 
 __stop = False 
 
 def __init__(self, interval = 0.5): 
  self.interval = interval 
  threading.Thread.__init__(self) 
 
 #Override 
 def run(self): 
  # logging.info('  Total  Finished  Percent  Speed') 
  print('  Total  Finished  Percent  Speed') 
  while not self.__stop: 
   time.sleep(self.interval) 
   if self.total_size > 0: 
    percent = self.finished_size / self.total_size * 100 
    speed = (self.finished_size - self.old_size) / self.interval 
    msg = '%12d %12d %10.2f%% %12d' % (self.total_size, self.finished_size, percent, speed) 
    # logging.info(msg) 
    print(msg) 
 
    self.old_size = self.finished_size 
   else: 
    logging.error('Total size is zero') 
  # ... end while statment 
 # ... end run() method 
 
 def stop(self): 
  self.__stop = True 
 
 def update(self, finished_size, total_size): 
  self.finished_size = finished_size 
  self.total_size = total_size 
 
class TestDownloaderFunctions(unittest.TestCase): 
 
 def setUp(self): 
  print('setUp') 
 
 def test_download(self): 
  url = 'http://dldir1.qq.com/qqfile/qq/QQ8.4/18376/QQ8.4.exe' 
  filename = 'QQ8.4.exe' 
  dl = Downloader(url, filename) 
  dl.download() 
 
 def tearDown(self): 
  print('tearDown') 
 
if __name__ == '__main__': 
 unittest.main()

这是测试结果:

Python编写一个优美的下载器

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python ElementTree 基本读操作示例
Apr 09 Python
pycharm 使用心得(六)进行简单的数据库管理
Jun 06 Python
Python OS模块常用函数说明
May 23 Python
python计算一个序列的平均值的方法
Jul 11 Python
Go/Python/Erlang编程语言对比分析及示例代码
Apr 23 Python
使用Python AIML搭建聊天机器人的方法示例
Jul 09 Python
python 实现dict转json并保存文件
Dec 05 Python
Python使用Excel将数据写入多个sheet
May 16 Python
详解Python中的编码问题(encoding与decode、str与bytes)
Sep 30 Python
pandas 操作 Excel操作总结
Mar 31 Python
Django实现聊天机器人
May 31 Python
python中urllib包的网络请求教程
Apr 19 Python
python实现音乐下载器
Apr 15 #Python
tensorflow 1.0用CNN进行图像分类
Apr 15 #Python
tensorflow学习笔记之mnist的卷积神经网络实例
Apr 15 #Python
tensorflow学习笔记之简单的神经网络训练和测试
Apr 15 #Python
Pytorch入门之mnist分类实例
Apr 14 #Python
pytorch构建网络模型的4种方法
Apr 13 #Python
Python输入二维数组方法
Apr 13 #Python
You might like
Apache+php+mysql在windows下的安装与配置图解(最新版)
2008/11/30 PHP
比较详细PHP生成静态页面教程
2012/01/10 PHP
php获取从百度搜索进入网站的关键词的详细代码
2014/01/08 PHP
Thinkphp 框架扩展之驱动扩展实例分析
2020/04/27 PHP
基于JQuery的一句话搞定手风琴菜单
2012/09/14 Javascript
浅析jQuery对select操作小结(遍历option,操作option)
2013/07/04 Javascript
JS连接SQL数据库与ACCESS数据库的方法实例
2013/11/21 Javascript
怎么限制input的text里输入的值只能是数字(正则、js)
2016/05/16 Javascript
清除输入框内的空格
2016/12/21 Javascript
js图片上传的封装代码
2017/08/01 Javascript
一个小时快速搭建微信小程序的方法步骤
2019/04/15 Javascript
layer.alert回调函数执行关闭弹窗的实例
2019/09/11 Javascript
ES10的13个新特性示例(小结)
2019/09/23 Javascript
Node.js web 应用如何封装到Docker容器中
2020/09/01 Javascript
Python基于动态规划算法计算单词距离
2015/07/25 Python
ubuntu系统下 python链接mysql数据库的方法
2017/01/09 Python
Python在图片中添加文字的两种方法
2017/04/29 Python
Python实现随机选择元素功能
2017/09/14 Python
Python复制Word内容并使用格式设字体与大小实例代码
2018/01/22 Python
Python HTML解析器BeautifulSoup用法实例详解【爬虫解析器】
2019/04/05 Python
分析运行中的 Python 进程详细解析
2019/06/22 Python
Scrapy框架基本命令与settings.py设置
2020/02/06 Python
基于python实现监听Rabbitmq系统日志代码示例
2020/11/28 Python
用HTML5 Canvas API中的clearRect()方法实现橡皮擦功能
2016/03/15 HTML / CSS
日本PLST在线商店:日本时尚杂志刊载的人气服装
2016/12/10 全球购物
ASOS英国官网:英国在线时装和化妆品零售商
2017/05/19 全球购物
servlet面试题
2012/08/20 面试题
自荐信格式范文
2013/10/07 职场文书
保护母亲河倡议书
2014/04/14 职场文书
最新离婚协议书范本
2014/08/19 职场文书
创建绿色社区汇报材料
2014/08/22 职场文书
2014年大学生社会实践自我鉴定
2014/09/26 职场文书
医院领导班子查摆问题对照检查材料思想汇报
2014/10/08 职场文书
再婚婚前财产协议书范本
2014/10/19 职场文书
2016年暑假家长对孩子评语
2015/12/01 职场文书
导游词之秦皇岛燕塞湖
2020/01/03 职场文书