Python,捕获OS输出并在discord中作为消息发送

时间:2016-07-30 21:43:33

标签: python-3.x subprocess python-asyncio

对于我正在制作的机器人,我希望能够查看运行它的pi的温度(当然命令只能由开发人员使用)。我的问题是我无法获取终端命令的输出。我知道命令一半有效,因为我可以在pi的屏幕上看到正确的输出,但机器人只发布一个" 0"聊天

我尝试过的事情:

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)

其中每个都做同样的事情,在聊天中发布0,在pi的屏幕上发布输出。如果有人可以提供帮助,我会非常感激

1 个答案:

答案 0 :(得分:2)

asyncio.subprocess模块允许您以异步方式处理子进程:

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)

查看asyncio user documentation中的更多示例。