This article mainly teaches you how to use Python to write a beautiful downloader. It has certain reference value. Interested friends can refer to it.
The example in this article shares with everyone the writing of a downloader in Python. The specific code is for your reference. The specific content is as follows
#!/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()
This is the test result:

Related recommendations:
Write a simple web crawler in Python to capture videos
##
The above is the detailed content of Write a beautiful downloader in Python. For more information, please follow other related articles on the PHP Chinese website!
Python: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AMPython excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
Python and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AMTo maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.
Python: Games, GUIs, and MoreApr 13, 2025 am 12:14 AMPython excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.
Python vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AMPython is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.
The 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AMYou can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.
Python: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AMPython is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.
How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PMYou can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.
How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AMHow to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),






