Python|AsyncIO|TypeError:应为协程

2022-03-25 00:00:00 python python-asyncio

问题描述

我正在尝试使用asyncio进行python协程编程。这是我的代码。

import asyncio

async def coro_function():
    return 2 + 2

async def get():
    return await coro_function()

print(asyncio.iscoroutinefunction(get))

loop = asyncio.get_event_loop()
a1 = loop.create_task(get)
loop.run_until_complete(a1)

但当我执行它时,它给我错误

True
Traceback (most recent call last):
  File "a.py", line 13, in <module>
    a1 = loop.create_task(get)
  File "/home/alie/anaconda3/lib/python3.7/asyncio/base_events.py", line 405, in create_task
    task = tasks.Task(coro, loop=self)
TypeError: a coroutine was expected, got <function get at 0x7fe1280b6c80>

如何解决?


解决方案

您传入的函数get

若要传入协程,请传入get()

a1 = loop.create_task(get())
loop.run_until_complete(a1)

查看类型:

>>> type(get)
<class 'function'>
>>> print(type(get()))
<class 'coroutine'>

get是协程函数,即返回协程对象get()的函数。有关更多信息和对基础知识的更好理解,请查看docs。

相关文章