python协程io自动切换--gevent-成都创新互联网站建设

关于创新互联

多方位宣传企业产品与服务 突出企业形象

公司简介 公司的服务 荣誉资质 新闻动态 联系我们

python协程io自动切换--gevent

1.gevent执行

无为ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

import gevent

def func1():
    print('func1 start')
    gevent.sleep(2)
    print('func1 end')

def func2():
    print('func2 start')
    gevent.sleep(1)
    print('func2 end')

def func3():
    print('func3 start')
    gevent.sleep(0)
    print('func3 end')

if __name__=='__main__':
    gevent.joinall([
        gevent.spawn(func1),
        gevent.spawn(func2),
        gevent.spawn(func3),

    ])

>>:
func1 start
func2 start
func3 start
func3 end
func2 end
func1 end       

2.gevent 中的mokey

from urllib import request
import gevent
import time
from gevent import monkey
monkey.patch_all()#把所有的io操作做上标记

def func(url):
    print('爬取地址:%s'%url)
    resp=request.urlopen(url)
    data=resp.read()
    print('%s地址的字节数为:%s'%(url,len(data)))

urls=['http://www.sina.com.cn/',
      'https://www.python.org',
      'https://github.com',
      ]
if __name__=='__main__':
    start_time=time.time()
    for url in urls:
        func(url)
    print("同步执行时间为:",time.time()-start_time)
    asvnc_start_time=time.time()
    gevent.joinall([
        gevent.spawn(func,'http://www.sina.com.cn/'),
        gevent.spawn(func,'https://www.python.org'),
        gevent.spawn(func,'https://github.com')

    ])
    print("异步执行时间为:", time.time() - asvnc_start_time)

>>:
爬取地址:http://www.sina.com.cn/
http://www.sina.com.cn/地址的字节数为:570200
爬取地址:https://www.python.org
https://www.python.org地址的字节数为:48834
爬取地址:https://github.com
https://github.com地址的字节数为:86520
同步执行时间为: 7.055272817611694
爬取地址:http://www.sina.com.cn/
爬取地址:https://www.python.org
爬取地址:https://github.com
http://www.sina.com.cn/地址的字节数为:570200
https://www.python.org地址的字节数为:48834
https://github.com地址的字节数为:59615
异步执行时间为: 2.019655466079712

分享标题:python协程io自动切换--gevent
标题链接:http://kswsj.cn/article/jjpgoi.html

其他资讯