05-02 协程gevent(monkey)的使用(并发)方便快捷

import gevent
import time
from gevent import monkey


# 这是一个补丁,代码中有耗时操作,换为gevent中自己实现的模块
monkey.patch_all()


def f(n):
	for i in range(n):
		print('---%d---' % i)
		time.sleep(0.5)

# gevent.joinall()实现多个协程同时工作,内部是一个列表。gevent.spawn()生成一个协程对象,供joinall协程使用
gevent.joinall([gevent.spawn(f,5),gevent.spawn(f,10)])

例题:爬取图片

import urllib.request
import gevent
from gevent import monkey


monkey.patch_all()

def mydownload(img_name,img_url):
	response = urllib.request.urlopen(img_url)
	content = response.read()
	with open(img_name,'wb') as fp:
		fp.write(content)


def main():
	gevent.joinall([gevent.spawn(mydownload, "1.jpg", "http://pic.topmeizi.com/wp-content/uploads/2017a/04/08/01.jpg"),
	gevent.spawn(mydownload, '2.jpg', 'http://pic.topmeizi.com/wp-content/uploads/2017a/04/07/01.jpg')])

你可能感兴趣的:(python)