python基于协程的网络库gevent、eventlet
python网络库也有了基于协程的实现,比较著名的是 gevent、eventlet 它两之间的关系可以参照
Comparing gevent to eventlet, 本文主要简单介绍一下eventlet一个例子
客户端:
import eventlet
from eventlet.green import urllib2
def myfetch(myurl, i):
req = urllib2.Request(myurl)
req.add_header('User-agent', 'Mozilla 5.10')
res = urllib2.urlopen(req, timeout = 4)
body = res.read();
size = len(body);
print (i, 'body size ' ,size)
return size
myurl = "http://127.0.0.1:6000"
pool = eventlet.GreenPool(1000)
for i in range(1, 200):
pool.spawn(myfetch, myurl, i)
#print i
pool.waitall()
print "--finish --GreenPool"
服务端:
#! /usr/bin/env python
"""\
Simple server that listens on port 6000 and echos back every input to
the client. To try out the server, start it up by running this file.
Connect to it with:
telnet localhost 6000
You terminate your connection by terminating telnet (typically Ctrl-]
and then 'quit')
"""
from __future__ import print_function
import eventlet
def handle(fd): #单个协程的处理逻辑
print("client connected")
while True:
# pass through every non-eof line
x = fd.readline()
if not x:
break
fd.write(x)
fd.flush()
print("echoed", x, end=' ')
print("client disconnected")
print("server socket listening on port 6000")
server = eventlet.listen(('0.0.0.0', 6000)) #监听6000端口
pool = eventlet.GreenPool() #构造协程池
while True:
try:
new_sock, address = server.accept() #accept新的连接
print("accepted", address)
pool.spawn_n(handle, new_sock.makefile('rw')) #将新的连接交由一个新的协程去处理
except (SystemExit, KeyboardInterrupt):
break
上面的例子可以看出eventlet接口还是非常的简洁和优雅的,至于稳定性和成熟度还待真实的场景去验证,
使用eventlet快速开发一个tcp/http的server还是非常迅速的,因为是基于协程的, 对于网络IO密集型的场景
速度不会太差.
eventlet已知的在openstack项目中有使用.
相关文章
- Python之——python-nmap的安装与常用方法说明
- 【Python】python 多线程两种实现方式
- python --help查询python相关命令
- Python 字符串_python 字符串截取_python 字符串替换_python 字符串连接
- Python视觉深度学习系列教程 第三卷 第1章 使用多个 GPU 训练网络
- Python 实例属性和类属性
- Python:更改默认启动的python程序及其对应的安装包路径(更改pip的默认安装包的路径)图文教程之详细攻略
- Python之matplotlib:基于matplotlib库利用python语言实现一张画布显示多张图的多种方法
- Python之tkinter:动态演示调用python库的tkinter带你进入GUI世界(Scale/Scale的Command)
- Python之tkinter:动态演示调用python库的tkinter带你进入GUI世界(text.insert/link各种事件)
- Python之API:基于python语言调用华为云API(华为网站)实现特定功能
- 已解决2.Set PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION=python (but this will use pure-Python parsing and wi
- 【负荷预测】基于贝叶斯网络的考虑不确定性的短期电能负荷预测(Python代码实现)
- 【华为机试真题 Python实现】路灯问题【2022 Q1 Q2 |200分】
- python基础===Python 迭代器模块 itertools 简介
- python之psutil模块(获取系统性能信息(CPU,内存,磁盘,网络)
- python基于协程的网络库gevent、eventlet
- 【Python基础】python爬虫之异步网络爬虫ǃ
- Python可视化数据分析01、python环境搭建