2016-07-30 27 views
1

對於一個機器人,我希望能夠查看運行它的pi的溫度(當然,該命令只能由開發人員使用)。我的問題是,我不能縫得到終端命令的輸出。我知道一個事實,即命令的一半工作,因爲我可以在pi的屏幕上看到正確的輸出,但機器人僅向聊天發佈「0」。Python,捕獲OS輸出併發送不一致的消息

東西我曾嘗試:

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的屏幕上的輸出。如果有人可以幫助,我會非常感激

回答

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更多的例子。