python中大文件的并发下载与处理

2024-04-24 23:36:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要下载的大文件的URL列表(例如压缩档案),我想处理这些文件(例如解压缩档案)。在

下载和处理都需要很长的时间,而且处理在磁盘IO上很繁重,所以我希望一次只运行一个。由于这两个任务占用的时间差不多,并且不会争夺相同的资源,所以我希望在处理最后一个任务时下载下一个文件。在

这是producer-consumer problem的变体。在

这种情况类似于reading and processing images或{a3},但我的下载器调用(还)不可选择,所以我无法使用多处理,而且两个任务的时间几乎相同。在

下面是一个虚拟示例,其中下载和处理都被阻塞:

import time
import posixpath

def download(urls):
    for url in urls:
        time.sleep(3)  # this is the download (more like 1000s) 
        yield posixpath.basename(url)

def process(fname):
    time.sleep(2)  # this is the processing part (more like 600s)

urls = ['a', 'b', 'c']
for fname in download(urls):
    process(fname)
    print(fname)

如何使这两个任务同时进行?我可以使用yieldyield fromin a smart way,也许与^{}结合使用吗?或者它必须是^{}和{}一起吗?在


Tags: 文件inimporturlfortimedownloaddef
2条回答

我只需使用threading.Thread(target=process, args=(fname,))并启动一个新线程进行处理。在

但在此之前,结束最后一个处理线程:

t = None
for fname in download(urls):
    if t is not None: # wait for last processing thread to end
        t.join()
    t = threading.Thread(target=process, args=(fname,))
    t.start()
    print('[i] thread started for %s' % fname)

https://docs.python.org/3/library/threading.html

一年后,我们实际上在使用python3的^{}和{a2}。在

相关问题 更多 >