python - python中的多线程文件下载并在shell中更新下载进度

标签 python multithreading download urllib2

为了学习多线程文件下载,我写了这个小菜一碟:

import urllib2
import os
import sys
import time
import threading

urls = ["http://broadcast.lds.org/churchmusic/MP3/1/2/nowords/271.mp3",
"http://s1.fans.ge/mp3/201109/08/John_Legend_So_High_Remix(fans_ge).mp3",
"http://megaboon.com/common/preview/track/786203.mp3"]

url = urls[1]

def downloadFile(url, saveTo=None):
    file_name = url.split('/')[-1]
    if not saveTo:
        saveTo = '/Users/userName/Desktop'
    try:
        u = urllib2.urlopen(url)
    except urllib2.URLError , er:
        print("%s" % er.reason)
    else:

        f = open(os.path.join(saveTo, file_name), 'wb')
        meta = u.info()
        file_size = int(meta.getheaders("Content-Length")[0])
        print "Downloading: %s Bytes: %s" % (file_name, file_size)
        file_size_dl = 0
        block_sz = 8192
        while True:
            buffer = u.read(block_sz)
            if not buffer:
                break

            file_size_dl += len(buffer)
            f.write(buffer)
            status = r"%10d  [%3.2f%%]" % (file_size_dl, file_size_dl * 100. / file_size)
            status = status + chr(8)*(len(status)+1)
            sys.stdout.write('%s\r' % status)
            time.sleep(.2)
            sys.stdout.flush()
            if file_size_dl == file_size:
                print r"Download Completed %s%% for file %s, saved to %s" % (file_size_dl * 100. / file_size, file_name, saveTo,)
        f.close()
        return


def synchronusDownload():
    urls_saveTo = {urls[0]: None, urls[1]: None, urls[2]: None}
    for url, saveTo in urls_saveTo.iteritems():
        th = threading.Thread(target=downloadFile, args=(url, saveTo), name="%s_Download_Thread" % os.path.basename(url))
        th.start()

synchronusDownload()

但似乎在启动第二次下载时,它会等待第一个线程,然后下载下一个文件,正如 shell 中打印的那样。

我的计划是同时开始所有下载并打印下载文件的更新进度。

任何帮助将不胜感激。 谢谢。

最佳答案

这是一个常见问题,以下是通常采取的步骤:

1.) 使用 Queue.Queue 创建一个包含您想要访问的所有 URL 的队列。

2.) 创建一个继承自threading.Thread的类。它应该有一个 run 方法,可以从队列中获取 url 并获取数据。

3.) 根据您的类创建一个线程池作为“workers”

4.) 在queue.join()完成之前不要退出程序

关于python - python中的多线程文件下载并在shell中更新下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24216760/

相关文章:

python - 索引到 numpy mgrid

Java:处理子线程中的异常

html - Flask 下载框

c# - 分段的 C# 文件下载器

python - 从当前时间获取小时

Python Pandas 使用滚动时间窗口进行计数

python - Gunicorn 和 Gevent 使 Heroku 上的 Flask 应用程序崩溃

Python:断言错误, "not called"

java - 如何用java开发类似生产者消费者的应用?

php - 从YouTube API批量下载图像