Python|AsyncIO|TypeError:应为协程 [英] Python | AsyncIO | TypeError: a coroutine was expected

查看:31
本文介绍了Python|AsyncIO|TypeError:应为协程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用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

这篇关于Python|AsyncIO|TypeError:应为协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆