[英]Python | AsyncIO | TypeError: a coroutine was expected
I'm trying python coroutine programming using asyncio.我正在尝试使用 asyncio 进行 python 协程编程。 This is my code.
这是我的代码。
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)
But when I execute it, it gives me error但是当我执行它时,它给了我错误
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>
How to solve it?如何解决?
You're passing in the function get
.您正在传递 function
get
。
In order to pass in a coroutine, pass in get()
.为了传入协程,传入
get()
。
a1 = loop.create_task(get())
loop.run_until_complete(a1)
Take a look at the types:看一下类型:
>>> type(get)
<class 'function'>
>>> print(type(get()))
<class 'coroutine'>
get
is a coroutine function , ie a function that returns a coroutine object, get()
. get
是协程function ,即 function 返回协程 object, get()
。 For more information and a better understanding of the fundamentals, take a look at the docs .有关更多信息和更好地理解基础知识,请查看文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.