关于程序员:Python异步-定义创建和运行协程5

2次阅读

共计 1386 个字符,预计需要花费 4 分钟才能阅读完成。

咱们能够在咱们的 Python 程序中定义协程,就像定义新的子例程(函数)一样。一旦定义,协程函数可用于创立协程对象。“asyncio”模块提供了在事件循环中运行协程对象的工具,事件循环是协程的运行时。

1. 如何定义协程

协程能够通过“async def”表达式定义。这是用于定义子例程的“def”表达式的扩大。它定义了一个能够创立的协程,并返回一个协程对象。

# define a coroutine
async def custom_coro():
    # ...

用“async def”表达式定义的协程被称为“协程函数”。

而后协程能够在其中应用特定于协程的表达式,例如 await、async for 和 async with。

# define a coroutine
async def custom_coro():
    # await another coroutine
    await asyncio.sleep(1)

2. 如何创立协程

一旦定义了协程,就能够创立它。这看起来像是在调用一个子程序。

...
# create a coroutine
coro = custom_coro()

这不会执行协程。它返回一个“协程”对象。“协程”Python 对象具备办法,例如 send() 和 close()。它是一种类型。

咱们能够通过创立协程实例并调用 type() 内置函数来报告其类型来证实这一点。

# SuperFastPython.com
# check the type of a coroutine
 
# define a coroutine
async def custom_coro():
    # await another coroutine
    await asyncio.sleep(1)
 
# create the coroutine
coro = custom_coro()
# check the type of the coroutine
print(type(coro))

运行示例报告创立的协程是一个“协程”类。咱们还会失去一个 RuntimeError,因为协程已创立但从未执行过,咱们将在下一节中探讨它。

<class 'coroutine'>
sys:1: RuntimeWarning: coroutine 'custom_coro' was never awaited

协程对象是可期待的。这意味着它是一个实现了 __await__() 办法的 Python 类型。

3. 如何从 Python 运行协程

能够定义和创立协程,但它们只能在事件循环中执行。执行协程的事件循环,治理协程之间的合作多任务处理。

启动协程事件循环的典型办法是通过 asyncio.run() 函数。此函数承受一个协程并返回协程的值。提供的协程能够用作基于协程的程序的入口点。

# SuperFastPython.com
# example of running a coroutine
import asyncio
# define a coroutine
async def custom_coro():
    # await another coroutine
    await asyncio.sleep(1)
 
# main coroutine
async def main():
    # execute my custom coroutine
    await custom_coro()
 
# start the coroutine program
asyncio.run(main())

当初咱们晓得如何定义、创立和运行协程,让咱们花点工夫理解事件循环。

本文由 mdnice 多平台公布

正文完
 0