搜尋
首頁後端開發Python教學python支持断点续传的多线程下载示例

复制代码 代码如下:

#! /usr/bin/env python
#coding=utf-8

from __future__ import unicode_literals

from multiprocessing.dummy import Pool as ThreadPool
import threading

import os
import sys
import cPickle
from collections import namedtuple
import urllib2
from urlparse import urlsplit

import time


# global lock
lock = threading.Lock()


# default parameters
defaults = dict(thread_count=10,
    buffer_size=10*1024,
    block_size=1000*1024)


def progress(percent, width=50):
    print "%s %d%%\r" % (('%%-%ds' % width) % (width * percent / 100 * '='), percent),
    if percent >= 100:
        print
        sys.stdout.flush()


def write_data(filepath, data):
    with open(filepath, 'wb') as output:
        cPickle.dump(data, output)


def read_data(filepath):
    with open(filepath, 'rb') as output:
        return cPickle.load(output)


FileInfo = namedtuple('FileInfo', 'url name size lastmodified')


def get_file_info(url):
    class HeadRequest(urllib2.Request):
        def get_method(self):
            return "HEAD"
    res = urllib2.urlopen(HeadRequest(url))
    res.read()
    headers = dict(res.headers)
    size = int(headers.get('content-length', 0))
    lastmodified = headers.get('last-modified', '')
    name = None
    if headers.has_key('content-disposition'):
        name = headers['content-disposition'].split('filename=')[1]
        if name[0] == '"' or name[0] == "'":
            name = name[1:-1]
    else:
        name = os.path.basename(urlsplit(url)[2])

    return FileInfo(url, name, size, lastmodified)


def download(url, output,
        thread_count = defaults['thread_count'],
        buffer_size = defaults['buffer_size'],
        block_size = defaults['block_size']):
    # get latest file info
    file_info = get_file_info(url)

    # init path
    if output is None:
        output = file_info.name
    workpath = '%s.ing' % output
    infopath = '%s.inf' % output

    # split file to blocks. every block is a array [start, offset, end],
    # then each greenlet download filepart according to a block, and
    # update the block' offset.
    blocks = []

    if os.path.exists(infopath):
        # load blocks
        _x, blocks = read_data(infopath)
        if (_x.url != url or
                _x.name != file_info.name or
                _x.lastmodified != file_info.lastmodified):
            blocks = []

    if len(blocks) == 0:
        # set blocks
        if block_size > file_info.size:
            blocks = [[0, 0, file_info.size]]
        else:
            block_count, remain = divmod(file_info.size, block_size)
            blocks = [[i*block_size, i*block_size, (i+1)*block_size-1] for i in range(block_count)]
            blocks[-1][-1] += remain
        # create new blank workpath
        with open(workpath, 'wb') as fobj:
            fobj.write('')

    print 'Downloading %s' % url
    # start monitor
    threading.Thread(target=_monitor, args=(infopath, file_info, blocks)).start()

    # start downloading
    with open(workpath, 'rb+') as fobj:
        args = [(url, blocks[i], fobj, buffer_size) for i in range(len(blocks)) if blocks[i][1]

        if thread_count > len(args):
            thread_count = len(args)

        pool = ThreadPool(thread_count)
        pool.map(_worker, args)
        pool.close()
        pool.join()


    # rename workpath to output
    if os.path.exists(output):
        os.remove(output)
    os.rename(workpath, output)

    # delete infopath
    if os.path.exists(infopath):
        os.remove(infopath)

    assert all([block[1]>=block[2] for block in blocks]) is True


def _worker((url, block, fobj, buffer_size)):
    req = urllib2.Request(url)
    req.headers['Range'] = 'bytes=%s-%s' % (block[1], block[2])
    res = urllib2.urlopen(req)

    while 1:
        chunk = res.read(buffer_size)
        if not chunk:
            break
        with lock:
            fobj.seek(block[1])
            fobj.write(chunk)
            block[1] += len(chunk)


def _monitor(infopath, file_info, blocks):
    while 1:
        with lock:
            percent = sum([block[1] - block[0] for block in blocks]) * 100 / file_info.size
            progress(percent)
            if percent >= 100:
                break
            write_data(infopath, (file_info, blocks))
        time.sleep(2)


if __name__ == '__main__':
    import argparse
    parser = argparse.ArgumentParser(description='Download file by multi-threads.')
    parser.add_argument('url', type=str, help='url of the download file')
    parser.add_argument('-o', type=str, default=None, dest="output", help='output file')
    parser.add_argument('-t', type=int, default=defaults['thread_count'], dest="thread_count", help='thread counts to downloading')
    parser.add_argument('-b', type=int, default=defaults['buffer_size'], dest="buffer_size", help='buffer size')
    parser.add_argument('-s', type=int, default=defaults['block_size'], dest="block_size", help='block size')

    argv = sys.argv[1:]

    if len(argv) == 0:
        argv = ['https://eyes.nasa.gov/eyesproduct/EYES/os/win']

    args = parser.parse_args(argv)

    start_time = time.time()
    download(args.url, args.output, args.thread_count, args.buffer_size, args.block_size)
    print 'times: %ds' % int(time.time()-start_time)

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
聊聊Node.js中的多进程和多线程聊聊Node.js中的多进程和多线程Jul 25, 2022 pm 07:45 PM

大家都知道 Node.js 是单线程的,却不知它也提供了多进(线)程模块来加速处理一些特殊任务,本文便带领大家了解下 Node.js 的多进(线)程,希望对大家有所帮助!

优化Java文件写入多线程性能的方法有哪些优化Java文件写入多线程性能的方法有哪些Jul 01, 2023 am 10:05 AM

Java开发中如何优化文件写入多线程并发性能在大规模数据处理的场景中,文件的读写操作是不可避免的,而且在多线程并发的情况下,如何优化文件的写入性能变得尤为重要。本文将介绍一些在Java开发中优化文件写入多线程并发性能的方法。合理使用缓冲区在文件写入过程中,使用缓冲区可以大大提高写入性能。Java提供了多种缓冲区实现,如ByteBuffer、CharBuffe

如何优化C++开发中的多线程调度效率如何优化C++开发中的多线程调度效率Aug 22, 2023 am 09:33 AM

在当今的软件开发领域中,多线程编程已经成为了一种常见的开发模式。而在C++开发中,多线程调度的效率优化是开发者需要关注和解决的一个重要问题。本文将围绕如何优化C++开发中的多线程调度效率展开讨论。多线程编程的目的是为了充分利用计算机的多核处理能力,提高程序运行效率和响应速度。然而,在并行执行的同时,多线程之间的竞争条件和互斥操作可能导致线程调度的效率下降。为

Python服务器编程:利用多线程解决并发问题Python服务器编程:利用多线程解决并发问题Jun 19, 2023 am 08:45 AM

随着互联网的发展,越来越多的应用程序被开发出来,它们需要处理并发请求。例如,Web服务器需要处理多个客户端请求。在处理并发请求时,服务器需要同时处理多个请求。这时候,Python中的多线程技术就可以派上用场了。本文将介绍如何使用Python多线程技术解决并发问题。首先,我们将了解什么是多线程。然后,我们将讨论使用多线程的优点和缺点。最后,我们将演示一个实例,

如何使用PHP多线程执行多个方法如何使用PHP多线程执行多个方法Mar 23, 2023 pm 02:11 PM

在PHP开发中,经常会遇到需要同时执行多个操作的情况。想要在一个进程中同时执行多个耗时操作,就需要使用PHP的多线程技术来实现。本文将介绍如何使用PHP多线程执行多个方法,提高程序的并发性能。

如何解决Java中遇到的代码性能优化问题如何解决Java中遇到的代码性能优化问题Jun 29, 2023 am 10:13 AM

如何解决Java中遇到的代码性能优化问题随着现代软件应用的复杂性和数据量的增加,对于代码性能的需求也变得越来越高。在Java开发中,我们经常会遇到一些性能瓶颈,如何解决这些问题成为了开发者们关注的焦点。本文将介绍一些常见的Java代码性能优化问题,并提供一些解决方案。一、避免过多的对象创建和销毁在Java中,对象的创建和销毁是需要耗费资源的。因此,当一个方法

Java错误:Java多线程数据共享错误,如何处理和避免Java错误:Java多线程数据共享错误,如何处理和避免Jun 25, 2023 am 11:16 AM

随着社会的发展和科技的进步,计算机程序已经渐渐成为我们生活中不可或缺的一部分。而Java作为一种流行的编程语言,以其可移植性、高效性和面向对象特性等而备受推崇。然而,Java程序开发过程中可能会出现一些错误,如Java多线程数据共享错误,这对于程序员们来说并不陌生。在Java程序中,多线程是非常常见的,开发者通常会使用多线程来优化程序的性能。多线程能够同时处

刨析swoole开发功能的多线程与多进程调度方式刨析swoole开发功能的多线程与多进程调度方式Aug 05, 2023 pm 01:43 PM

刨析swoole开发功能的多线程与多进程调度方式随着互联网技术的发展,对服务器性能的要求越来越高。在高并发场景下,传统的单线程模型往往无法满足需求,因此诞生了多线程和多进程调度方式。swoole作为一种高性能的网络通信引擎,提供了多线程和多进程的开发功能,本文将对其进行深入分析和探讨。一、多线程调度方式线程概念介绍线程是操作系统能够进行运算调度的最小单位。在

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前By尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
1 個月前By尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具