Async初识
# Author:Luo
import asyncio
import threading
import random
@asyncio.coroutine # 说明符,可以当做注解来看
def hello():
print("Hello Up", threading.current_thread().getName())
yield from asyncio.sleep(random.randint(1,3)) # 一个阻塞了会运行另一个
print("Hello down",threading.current_thread().getName())
loop = asyncio.get_event_loop() # 异步任务
tasks=[hello(),hello(),hello()] # 三个任务
loop.run_until_complete(asyncio.wait(tasks)) # 等待运行完成任务
loop.close() # 关闭任务
异步下载
# Author:Luo
import asyncio
# yield from 等效于await
def download(url):
print("download", url)
connect = asyncio.open_connection(url, 80) # 打开网页服务器端口
reader, writer = yield from connect # 等待链接打开成功
header = "GET / HTTP/1.0\r\nHost:%s\r\n\r\n" % url # 生成访问头
writer.write(header.encode("utf-8"))
yield from writer.drain() # 等待上面的header写完
while True:
line = yield from reader.readline() # 读取完成
if line == b"\r\n":
break
print("%s header >%s" % (url, line.decode("utf-8"))) # 打印下信息
writer.close()
loop = asyncio.get_event_loop() # 协程异步循环
tasks = [download(url=url) for url in ["www.1000phone.com",
"www.mobiletrain.org"]] # 生成任务列表
loop.run_until_complete(asyncio.wait(tasks)) # 等待任务完成
loop.close()
异步下载Async
# Author:Luo
import asyncio
# yield from 等效于await
async def download(url):
print("download", url)
connect = asyncio.open_connection(url, 80) # 打开网页服务器端口
reader, writer = await connect # 等待链接打开成功
header = "GET / HTTP/1.0\r\nHost:%s\r\n\r\n" % url # 生成访问头
writer.write(header.encode("utf-8"))
await writer.drain() # 等待上面的header写完
while True:
line = await reader.readline() # 读取完成
if line == b"\r\n":
break
print("%s header >%s" % (url, line.decode("utf-8"))) # 打印下信息
writer.close()
loop = asyncio.get_event_loop() # 协程异步循环
tasks = [download(url=url) for url in ["www.1000phone.com",
"www.mobiletrain.org"]] # 生成任务列表
loop.run_until_complete(asyncio.wait(tasks)) # 等待任务完成
loop.close()