简体   繁体   English

Python - 使用等待的 function Asyncio 的返回变量

[英]Python - Using the return variable of an awaited function Asyncio

I'm coding a small class that should be able to turn lights on when I receive an "ON" message from the mqtt broker.我正在编写一个小型 class,当我收到来自 mqtt 代理的“ON”消息时,它应该能够打开灯。 The issue I'm having is that the conn() function connects, and retrieves the message while the on_message() function awaits this.我遇到的问题是conn() function 连接并检索消息,而on_message() function 等待这个。 I haven't been able to use the message as I'm awaiting it and I cant find a solution to do this within the await (usually you just do message = conn() , when conn() returns the message).我无法使用该消息,因为我正在等待它,并且我无法在等待中找到解决方案(通常你只需执行message = conn() ,当conn()返回消息时)。 The code below was one of the attempts:下面的代码是尝试之一:

class SpaceCode:

    def __init__(self, subscription, broker):
        self.subscription = subscription
        self.broker = broker

    def turn_off(self, message):
        pass

    async def conn(self):
        async with Client(self.broker) as client:
            async with client.filtered_messages(self.subscription) as messages:
                await client.subscribe(self.subscription)
                async for message in messages:
                    return message

    async def main(self):
        try:
            await asyncio.wait_for(self.movement_detected(), timeout=900)
        except asyncio.TimeoutError:
            turn_off(topic)

    async def movement_detected(self):
        await self.on_message()

    async def on_message(self):
        await self.conn()
        message = self.conn()
        if "ON" in str(message.payload.decode("utf-8")):  
            return str(message.payload.decode("utf-8"))

The error it returns then is "AttributeError:'coroutine' object has no attribute payload" which makes sense, I used a coroutine I did not await but even when just doing await message = self.conn() it will result in an error.然后它返回的错误是“AttributeError:'coroutine' object 没有属性有效负载”,这是有道理的,我使用了一个我没有等待的协程,但即使只是执行await message = self.conn()也会导致错误。

Thanks to @NobbyNobbs, the solution was to to await the coroutine and assign it to the variable at the same time.感谢@NobbyNobbs,解决方案是等待协程并同时将其分配给变量。 My version:我的版本:

await self.conn()
message = self.conn()

The correct version:正确的版本:

await message = self.conn()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM