user6641547
user6641547

Reputation:

Python, capture OS output and send as a message in discord

For a bot im making i want to be able to view the temperature of the pi running it (of course the command can only be used by a dev). My issue is that i cant seam to get the output of the terminal command. I know for a fact that the command half works, because I can see the correct output on the pi's screen, but the bot only posts a "0" to the chat.

Things i have tried:

async def cmd_temp(self, channel):
    proc = subprocess.Popen('/opt/vc/bin/vcgencmd measure_temp',
                            stdout=subprocess.PIPE)
    temperature = proc.stdout.read()
    await self.safe_send_message(channel, temperature)


async def cmd_temp(self, channel):
    await self.safe_send_message(channel,
        (os.system("/opt/vc/bin/vcgencmd measure_temp")))


async def cmd_temp(self, channel):
    temperature = os.system("/opt/vc/bin/vcgencmd measure_temp")
    await self.safe_send_message(channel, temperature)

Each of these does the same thing, posts a 0 in the chat, and the output on the screen of the pi. If anyone can help, i'd greatly appreciate it

Upvotes: 1

Views: 747

Answers (1)

Vincent
Vincent

Reputation: 13415

The asyncio.subprocess module lets you deal with subprocesses in an asynchronous manner:

async def cmd_temp(self, channel):
    process = await asyncio.create_subprocess_exec(
        '/opt/vc/bin/vcgencmd', 
        'measure_temp', 
        stdout=subprocess.PIPE)
    stdout, stderr = await process.communicate()
    temperature = stdout.decode().strip()
    await self.safe_send_message(channel, temperature)

See more examples in the asyncio user documentation.

Upvotes: 2

Related Questions