python中使用asyncio实现异步IO实例分析
作者:小妮浅浅 时间:2021-02-06 10:02:50
1、说明
Python实现异步IO非常简单,asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持。
asyncio的编程模型就是一个消息循环。我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO。
2、实例
import asyncio
@asyncio.coroutine
def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = yield from connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
yield from writer.drain()
while True:
line = yield from reader.readline()
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').rstrip()))
# Ignore the body, close the socket
writer.close()
loop = asyncio.get_event_loop()
tasks = [wget(host) for host in ['www.sina.com.cn', 'www.sohu.com', 'www.163.com']]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
知识点扩展:
数据流(Streams)
数据流(Streams)是用于处理网络连接的高阶异步/等待就绪(async/await-ready)原语,可以在不使用回调和底层传输协议的情况下发送和接收数据。
以下是一个用asyncio实现的TCP回显客户端:
import asyncio
async def tcp_echo_client(message):
reader, writer = await asyncio.open_connection(
'127.0.0.1', 8888)
print(f'Send: {message!r}')
writer.write(message.encode())
data = await reader.read(100)
print(f'Received: {data.decode()!r}')
print('Close the connection')
writer.close()
await writer.wait_closed()
asyncio.run(tcp_echo_client('Hello World!'))
来源:https://www.py.cn/jishu/jichu/27109.html
标签:python,asyncio,异步IO
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
oracle应用程序实现打包 的方法
2009-03-02 10:32:00
用SQL统计SQLServe表存储空间大小的代码
2012-06-06 19:52:22
另外一种斜体的导航条
2008-11-05 12:24:00
asp伪静态情况下实现的utf-8文件缓存实现代码
2011-02-24 10:49:00
用XMLHTTP很好的一个例子
2008-04-25 10:25:00
Python中easy_install 和 pip 的安装及使用
2023-08-24 13:34:54
Python编程对列表中字典元素进行排序的方法详解
2023-11-23 04:48:26
PHP访问MySQL查询超时处理的方法
2023-11-23 03:05:48
![](https://img.aspxhome.com/file/2023/2/85812_0s.jpg)
让IE8支持eWebEditor在线编辑器
2010-02-28 10:36:00
Asp无组件生成缩略图
2007-10-26 12:08:00
python3实现读取chrome浏览器cookie
2023-10-18 13:18:44
保护SQL服务器的安全 用户识别问题
2008-12-24 15:26:00
![](https://img.aspxhome.com/file/UploadPic/200812/20081225122629996.jpg)
block 和 inline 的区别是?
2009-12-08 13:00:00
![](https://img.aspxhome.com/file/UploadPic/200912/8/203330321-54s.gif)
商业价值与用户价值的平衡
2008-12-10 18:42:00
![](https://img.aspxhome.com/file/UploadPic/200812/10/002_small-39s.jpg)
如何利用SysOjects来获知数据库的信息?
2010-01-01 15:43:00
错误的随机数_JavaScript
2009-08-28 12:43:00
python中Requests发送json格式的post请求方法
2021-05-24 10:09:45
![](https://img.aspxhome.com/file/2023/3/66773_0s.png)
asp如何制作一个倒计时的程序?
2010-06-29 21:25:00
js验证表单(form)中的单选(radio)值
2008-03-18 13:23:00
Python 函数装饰器应用教程
2022-08-17 05:53:24