标签:
eventlet的monkey_patch 用于绿化一些python的模块,看看以下的样例就明确了
urls = ["http://www.haha.mx/joke/1292935",
"http://www.baidu.com"]
import eventlet
from eventlet.green import urllib2
import time
def fetch(url):
try:
print "opening0", url
time.sleep(1)
body = urllib2.urlopen(url).read()
print "done with0", url
return url, body
except urllib2.HTTPError:
return "",""
def fetch1(url):
try:
print "opening1", url
body = urllib2.urlopen(url).read()
print "done with1", url
return url, body
except urllib2.HTTPError:
return "",""
eventlet.monkey_patch()
pool = eventlet.GreenPool(100)
pool.spawn(fetch,urls[0])
pool.spawn(fetch1,urls[1])
pool.waitall()
执行结果:
opening0 http://www.haha.mx/joke/1292935
opening1 http://www.baidu.com
done with1 http://www.baidu.com
done with0 http://www.haha.mx/joke/1292935
monkey_patch函数原型:
monkey_patch(os=None, select=None, socket=None, thread=None, time=None, psycopg=None)
程序中在pool中创建两个绿色线程用于处理fetch和fetch1,fetch和fetch1不同的是fetch中调用了time.sleep(1),并且使用eventlet.monkey_patch()对time模块进行了绿化,从执行结果能够看出,先处理的处理的fetch,只是在fetch函数用调用time.sleep(1)将执行权利交给了hub,然后接着执行fetch1,假设不使用monkey_patch的话time.sleep(1)会堵塞。这就是monke_patch的奇妙之处,它在程序開始的时候调用相当于一个开关,并且能够通过monkey_patch的參数指定要绿化的模块。
Green the world :使用monkey_patch
标签:
原文地址:http://www.cnblogs.com/gcczhongduan/p/4297470.html