import gevent
import urllib.request #网络请求模块
from gevent import monkey
monkey.patch_all()
def download_file(file_url, file_name):
try:
response = urllib.request.urlopen(file_url)
# 网络图片数据
with open(file_name,"wb") as img_file:
while True:
file_data = response.read(1024)
if file_data:
img_file.write(file_data)
else:
break
except Exception as e:
print("文件下载异常:", e)
else:
print("文件下载成功:%s" %file_name)
if __name__ == '__main__':
file_url1 ="文件地址1"
file_url2 = "文件地址2"
# 创建协程指派对应的任务
g1 = gevent.spawn(download_file, file_url1,"1.文件扩展名")
g2 = gevent.spawn(download_file, file_url2,"2.文件扩展名")
# 主线程等待所有的协程执行完成以后程序再退出
gevent.joinall([g1 ,g2 ])
使用gevent进行文件下载
最新推荐文章于 2022-08-08 17:30:45 发布