【问题标题】:Python, capture OS output and send as a message in discordPython,捕获操作系统输出并作为不和谐的消息发送
【发布时间】:2016-07-30 21:43:33
【问题描述】:

对于一个正在制作的机器人,我希望能够查看运行它的 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 的屏幕上输出。如果有人可以提供帮助,我将不胜感激

【问题讨论】:

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


    【解决方案1】:

    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 中查看更多示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-12
      • 2021-01-10
      • 1970-01-01
      • 2022-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-13
      相关资源
      最近更新 更多