同时使用多进程在Python中下载文件



我在下面制作了一个代码,用于使用pysmartdl下载文件。我想一次下载多个文件。试图使用多进程实现它。但是第二个过程仅在第一次完成时才开始。代码如下:

import time
from multiprocessing import Process
from pySmartDL import SmartDL, HashFailedException    
def down():
    dest='/home/faheem/Downloads'
    obj = SmartDL(url_100mb_file,dest, progress_bar=False,fix_urls=True)
    obj.start(blocking=False)
    #cnt=1
    while not obj.isFinished():
            print("Speed: %s" % obj.get_speed(human=True))
            print("Already downloaded: %s" % obj.get_dl_size(human=True))
            print("Eta: %s" % obj.get_eta(human=True))
            print("Progress: %d%%" % (obj.get_progress()*100))
            print("Progress bar: %s" % obj.get_progress_bar())
            print("Status: %s" % obj.get_status())
            print("n"*2+"="*50+"n"*2)
            print("SIZE=%s"%obj.filesize)
            time.sleep(2)
    if obj.isSuccessful():
            print("downloaded file to '%s'" % obj.get_dest())
            print("download task took %ss" % obj.get_dl_time(human=True))
            print("File hashes:")
            print(" * MD5: %s" % obj.get_data_hash('md5'))
            print(" * SHA1: %s" % obj.get_data_hash('sha1'))
            print(" * SHA256: %s" % obj.get_data_hash('sha256'))
            data=obj.get_data()
    else:
            print("There were some errors:")
            for e in obj.get_errors():
                    print(str(e))
    return
if __name__ == '__main__':
    #jobs=[]
    #for i in range(5):
    print 'Link1'
    url_100mb_file = ['https://softpedia-secure-download.com/dl/45b1fc44f6bfabeddeb7ce766c97a8f0/58b6eb0f/100255033/software/office/Text%20Comparator%20(v1.2).rar']
    Process(target=down()).start()
    print'link2'
    url_100mb_file = ['https://www.crystalidea.com/downloads/macsfancontrol_setup.exe']
    Process(target=down()).start()

在此处,link2在链接1结束时开始下载,但是我都需要下载才能同时执行。我想实现此方法一次执行10个下载。那么使用多处理好吗?还有其他更好的内存有效方法吗?我是这些代码的初学者,因此很容易定义答案。问候

您也可以使用Python模块Thread。这是有关其工作方式的一些小片段:

import threading
import time
def func(i):
        time.sleep(i)
        print i
for i in range(1, 11):
        thread = threading.Thread(target = func, args=(i,))
        thread.start()
        print "Launched thread " + str(i)
print "Done"

运行此片段,您将对它的工作方式有一个完美的想法。知道这一点,您实际上可以运行代码,以参数作为参数传递给url在每个线程中使用的函数。

希望有帮助

您正在使用的特定库似乎已经支持非阻止下载,那么为什么不做以下内容呢?非阻滞意味着它将在单独的过程中运行。

from time import sleep
from pySmartDL import SmartDL 
links = [['https://softpedia-secure download.com/dl/45b1fc44f6bfabeddeb7ce766c97a8f0/58b6eb0f/100255033/software/office/Text%20Comparator%20(v1.2).rar'],['https://www.crystalidea.com/downloads/macsfancontrol_setup.exe']]
objs = [SmartDL(link, progress_bar=False) for link in links]
for obj in objs:
    obj.start(blocking=False)
while not all(obj.isFinished() for obj in objs):
     sleep(1)

由于您的程序是i/o-bound,因此您可以使用多处理多线程。

以防万一,我想提醒经典模式,以解决此类问题。有一个URL的队列,从该URL从该URL中提取处理URL进行处理,并以一个状态队列推出其进度报告或错误。

与手动控制相比

最新更新