微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Python 异步函数返回协程对象

如何解决Python 异步函数返回协程对象

我正在运行一个 python 程序来收听 azure iot hub。该函数返回一个协程对象而不是一个 json。我看到如果我们使用 async 函数并将其作为普通函数调用会发生这种情况,但我创建了一个循环来获取事件,然后使用 run_until_complete 函数。我在这里错过了什么?

async def main():
    try:
        client = IoTHubModuleClient.create_from_connection_string(connection_string)
        print(client)
        client.connect() 
        while True:
            message = client.receive_message_on_input("input1")   # blocking call
            print("Message received on input1")
            print(type(message))
            print(message)

        
    except KeyboardInterrupt:
        print ( "IoTHubClient sample stopped" )
    except:
        print ( "Unexpected error from IoTHub" )
        return

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())
    loop.close()

输出- 在 input1 上收到消息

解决方法

长话短说:你只需要写 await client.receive_message_on_input("input1")。您的 main 是一个协程,但 receive_message_on_input 也是一个协程。您必须等待它完成。 我可以告诉你这个故事,但它真的太长了。 :)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。