代码拉取完成,页面将自动刷新
# -*- 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()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。