python 事件机制asyncio(并行编程 25)

loop=get_event_loop() 当前上下文的事件循环

loop.call_later(time_delay,callback,arg)

loop.call_soon(callback,agr)

asyncio.set_event_loop() 设定上下文事件循环

asyncio.new_event_loop() 创建

loop.run_forever()

异步函数:

import time
import asyncio

定义异步函数

async def hello():
print('Hello World:%s' % time.time())

def run():
for i in range(5):
loop.run_until_complete(hello())

loop = asyncio.get_event_loop()
if name =='main':
run()

输出结果:

Hello World:1562248241.350658
Hello World:1562248241.350658
Hello World:1562248241.350658
Hello World:1562248241.350658
Hello World:1562248241.350658


异步requests库:aiohttp

import asyncio
from aiohttp import ClientSession

tasks = []
url = "https://www.baidu.com/{}"
async def hello(url):
async with ClientSession() as session:
async with session.get(url) as response:
response = await response.read()
print(response)

if name == 'main':
loop = asyncio.get_event_loop()
loop.run_until_complete(hello(url))


import asyncio

async def main():
print('Hello ...')
await asyncio.sleep(1)
print('... World!')

Python 3.7+

asyncio.run(main())

你可能感兴趣的:(python 事件机制asyncio(并行编程 25))