Chi*_*yak 12 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)
Run Code Online (Sandbox Code Playgroud)
但是当我执行它时,它给了我错误
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>
Run Code Online (Sandbox Code Playgroud)
怎么解决呢?
Alg*_*ra8 21
您正在传递 function get。
为了传入协程,请传入get().
a1 = loop.create_task(get())
loop.run_until_complete(a1)
Run Code Online (Sandbox Code Playgroud)
看一下类型:
>>> type(get)
<class 'function'>
>>> print(type(get()))
<class 'coroutine'>
Run Code Online (Sandbox Code Playgroud)
get是一个协程函数,即返回协程对象的函数get()。要了解更多信息并更好地理解基础知识,请查看文档。