简体   繁体   中英

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. The issue I'm having is that the conn() function connects, and retrieves the message while the on_message() function awaits this. 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). 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.

Thanks to @NobbyNobbs, the solution was to to await the coroutine and assign it to the variable at the same time. My version:

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

The correct version:

await message = self.conn()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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