ThreadPoolExecutor

发布时间 2024-01-09 11:38:43作者: howhy
from concurrent.futures.thread import  ThreadPoolExecutor
import requests
song_list=[
    {'title':'胡广生.mp3','url':'https://webfs.hw.kugou.com/202401081759/c31a8ef4b3a90566ef3edc50b0ba89cf/v2/8c655f575ebb2414b53eff0d2c13188d/G239/M0B/10/17/j4cBAF-iFpOAfy28ADSAwjCjhSY182.mp3'},
    {'title':'爱的尽头.mp3','url':'https://webfs.tx.kugou.com/202401081803/03783d35c65c56c15f1dc22ec6b0b60f/v2/e3e5d6f3505fc4bd5fe145fd810fc431/G312/M05/43/74/GJUEAGVa7GGAKDupAFek4771K10136.mp3'},
    {'title': '直到世界尽头.mp3',
     'url': 'https://webfs.hw.kugou.com/202401081804/535a2fd592ea6cf53002ef291b29dcdd/v2/19e030ab78dc0ea613ee5b71b250abd3/part/0/960169/G324/M0B/A4/57/clip_JJUEAGTTXSCAbZn7AEqqboHJhh0589.mp3'},
]
def downUrl(url):
    return requests.get(url).content
def save(filename):
    def done(ret):
        ret=ret.result()
        with open('%s'%filename,'wb') as fw:
            fw.write(ret)
    return done
pool=ThreadPoolExecutor(4)
for song in song_list:
    title=song.get('title')
    url = song.get('url')
    task=pool.submit(downUrl,url=url)
    task.add_done_callback(save(title))