python异步_Python中的异步方法调用?

从Python 3.5开始,您可以将增强的生成器用于异步功能。

import asyncio

import datetime

增强的生成器语法:

@asyncio.coroutine

def display_date(loop):

end_time = loop.time() + 5.0

while True:

print(datetime.datetime.now())

if (loop.time() + 1.0) >= end_time:

break

yield from asyncio.sleep(1)

loop = asyncio.get_event_loop()

# Blocking call which returns when the display_date() coroutine is done

loop.run_until_complete(display_date(loop))

loop.close()

新async/await语法:

async def display_date(loop):

end_time = loop.time() + 5.0

while True:

print(datetime.datetime.now())

if (loop.time() + 1.0) >= end_time:

break

await asyncio.sleep(1)

loop = asyncio.get_event_loop()

# Blocking call which returns when the display_date() coroutine is done

loop.run_until_complete(display_date(loop))

loop.close()

你可能感兴趣的:(python异步)