加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
py39-asyncio.py 1.64 KB
一键复制 编辑 原始数据 按行查看 历史
eddiechow 提交于 2018-02-08 14:33 . demo增加
# -*- coding:utf-8 -*-
"""asyncio 异步IO"""
__author__ = 'Eddie Chow'
import asyncio
import threading
@asyncio.coroutine
def hello():
print('Hello World! (%s)' % threading.currentThread())
# 后续代码不会阻塞主线程,都是同一个线程
r = yield from asyncio.sleep(1)
print('Hello again! (%s)' % threading.currentThread())
async def hello_async():
"""
从Python 3.5 开始引入的新语法,async 替换 @asyncio.coroutine,await 替换 yield from
:return:
"""
print('Hello world (%s)' % threading.currentThread())
r = await asyncio.sleep(1)
print('Hello again (%s)' % threading.currentThread())
async def wget(host):
print('wget %s...' % host)
connect = asyncio.open_connection(host, 80)
reader, writer = await connect
header = 'GET / HTTP/1.0\r\nHost: %s\r\n\r\n' % host
writer.write(header.encode('utf-8'))
await writer.drain()
while True:
line = await reader.readline()
if line == b'\r\n':
break
print('%s header > %s' % (host, line.decode('utf-8').strip()))
writer.close()
if __name__ == '__main__':
# loop = asyncio.get_event_loop()
# tasks = [hello(), hello()]
# loop.run_until_complete(asyncio.wait(tasks))
# loop.close()
# 异步网络连接获取sina sohu 163 首页
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()
# loop = asyncio.get_event_loop()
# tasks = [hello_async(), hello_async()]
# loop.run_until_complete(asyncio.wait(tasks))
# loop.close()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化