zl程序教程

您现在的位置是:首页 >  后端

当前栏目

python实现 协程多任务图片下载器

Python 实现 协程 多任务
2023-09-14 09:07:32 时间

 

 

import urllib.request
import gevent
from gevent import monkey
monkey.patch_all()

def main():
    urlList = ['http://10.194.116.146/CSSImg/hkjc_logo.png', 'http://10.194.109.125/Content/Swagger.png', 'http://10.194.109.125/favicon.ico']
    fileNameList = ["4.png", "5.png", "6.png"]

    ge = gevent.spawn(downloadImages, urlList, fileNameList)
    ge.join()


def downloadImages(urlList, fileNameList):
    i = 0
    for value in urlList:
        response_data = urllib.request.urlopen(value)
        with open(fileNameList[i], "wb") as file:
            while True:
                file_data = response_data.read(1024)
                if file_data:
                    file.write(file_data)
                else:
                    break
        i += 1

if __name__ == '__main__':
    main()