标签:color 机制 function rgba 时间循环 sha pass 不包含 for
事件循环是asyncio提供的核心运行机制
column | column |
asyncio.get_event_loop() | 返回一个事件循环对象,时asyncio.BaseEventLoop的实例 |
AbstractEventLoop.stop() | 停止运行事件循环 |
AbstractEventLoop.run_forever() | 一直运行,直到stop() |
AbstractEventLoop.run_until_complete(future) | 运行直至future对象运行完 |
AbstractEventLoop.close() | 关闭事件循环对象 |
AbstractEventLoop.is_running() | 返回事件循环对象是否运行 |
Abstract Event Loop.close() | 关闭事件循环 |
协程:
协程是用户空间调度完成并发处理的方式
进程,线程由OS完成调度,而协程是线程内完成调度,它不需要更多线程,没有多线程切换带来的开销
协程是非抢占式调度,只有一个协程主动让出控制权,另一个协程才会被调度
协程也不需要使用锁机制,因为是在同一线程中执行
多CPU下,可以使用多进程和协程配合,既能 进程并发又能发挥协程在单线程中的优势
python中协程是基于生成器的
协程的使用:
import asyncio
async def sleep(b):
for i in range(3):
print(‘sleep {}‘.format(i))
await asyncio.sleep(i)
loop=asyncio.get_event_loop()
loop.run_until_complete(sleep(3))
loop.close()
async def 用来定义协程函数,iscoroutinefunction()返回True,协程函数中可以不包含await async关键字,但是不能使用yield关键字
如同生成器函数调用返回生成器对象,协程函数调用也会返回一个对象称为协程对象,
iscoroutine()返回True
iscoroutinefunction()
import asyncio,threading async def sleep(b): for v in range(3): print(‘sleep {}‘.format(v)) await asyncio.sleep(b) async def show(): for _ in range(3): print(threading.enumerate()) await asyncio.sleep(2) print(asyncio.iscoroutinefunction(sleep)) print(asyncio.iscoroutine(sleep)) print(asyncio.iscoroutine(sleep(3))) loop=asyncio.get_event_loop() tasks=[sleep(3),show()] loop.run_until_complete(asyncio.wait(tasks)) loop.close()
TCP Echo Server
import asyncio async def handle(reader,writer): while True: datum=await reader.read(1024) print(dir(reader)) print(dir(writer)) client=writer.get_extra_info(‘peername‘) message=‘{} = {}‘.format(client,datum.decode()).encode() writer.write(message) await writer.drain() loop=asyncio.get_event_loop() crt=asyncio.start_server(handle,‘‘,9999,loop=loop) server=loop.run_until_complete(crt) print(server) try: loop.run_forever() except KeyboardInterrupt: pass finally: server.close() loop.close()
aiohttp
HTTP Server
from aiohttp import web async def indexhandle(request:web.Request): return web.Response(text=request.path,status=201) async def handle(request:web.Request): print(request.match_info) print(request.query_string) return web.Response(text=request.match_info.get(‘id‘,‘000‘),status=200) app=web.Application() app.router.add_get(‘/‘,indexhandle) app.router.add_get(‘/{id}‘,handle) web.run_app(app,host=‘0.0.0.0‘,port=9988)
HTTP Client
import asyncio from aiohttp import ClientSession async def get_html(url:str): async with ClientSession() as session: async with session.get(url) as res: print(res.status) print(await res.text()) url=‘http://www.baidu.com‘ loop=asyncio.get_event_loop() loop.run_until_complete(get_html(url)) loop.close()
时间循环 asyncio 协程
标签:color 机制 function rgba 时间循环 sha pass 不包含 for
原文地址:https://www.cnblogs.com/dissipate/p/13940798.html
暂无评论...