2016-12-14 35 views
0

我正在玩坐在我的Raspberry Pi上的電報機器人,所有工作都很好,但我試圖用命令/正常運行時間顯示rpi的正常運行時間,但未嘗試:Python中的電子郵件正常運行時間

elif command == '/uptime': 
    bot.sendMessage(chat_id, os.system("uptime")) 

elif command == '/uptime': 
    uptime = os.system("uptime") 
    bot.sendMessage(chat_id,'%s' % uptime) 

現在,這是我最後一次,不成功,嘗試:

elif command == '/uptime': 
    uptime = os.popen("awk '{print $1}' /proc/uptime").readline() 
    bot.sendMessage(chat_id, ('uptime(sec) = '+uptime)) 

在哪裏錯誤?

下面是完整的代碼:

import sys 
import os 
import telepot 
import datetime 
import time 
from datetime import timedelta 

id_a = [111111,2222222,3333333,4444444,5555555] 

def handle(msg): 
    chat_id = msg['chat']['id'] 
    command = msg['text'] 
    sender = msg['from']['id'] 


    print 'Got command: %s' % command 

    if sender in id_a: 
    if command == '/ciao': 
      bot.sendMessage(chat_id, 'Hei, ciao!') 
    elif command == '/apri': 
     os.system("sudo python /home/pi/tg/xyz.py") 
     bot.sendMessage(chat_id, 'Ti ho aperto!') 
    elif command == '/uptime': 
     with open('/proc/uptime', 'r') as f: 
     usec = float(f.readline().split()[0]) 
     usec_str = str(timedelta(seconds = usec)) 
     bot.sendMessage(chat_id, '%s' % usec_str) 
    elif command == '/riavvia': 
      bot.sendMessage(chat_id, 'Rebooting...') 
      os.system("sudo reboot") 
    else: 
     bot.sendMessage(chat_id, 'Forbidden access!') 
     bot.sendMessage(chat_id, sender) 

bot = telepot.Bot('myToken') 
bot.message_loop(handle) 
print 'I am listening ...' 

while 1: 
    time.sleep(10) 
+0

也嘗試: elif的命令== '/正常運行時間': 正常運行時間= subprocess.check_output([ '運行時間']) 打印 '',正常運行時間 bot.sendMessage(chat_id,STR(正常運行時間)) – fdicarlo

回答

0

的Try ...

from datetime import timedelta 

with open('/proc/uptime', 'r') as f: 
    usec = float(f.readline().split()[0]) 
    usec_str = str(timedelta(seconds = usec)) 
    # and send message usec_str 
+0

不幸的是沒有,在這裏如何修改: elif command =='/ uptime': with open('/ proc/uptime','r')as f: usec = float(f.readline().split() [0]) usec_str = str(timedelta(seconds = usec)) bot.sendMessage(chat_id,'%s'%usec_str) – fdicarlo

+0

@fdicarlo你的發送消息函數或bot對象是什麼樣的? – moogle

+0

嗨@moogle我添加了代碼 – fdicarlo

0

你需要得到來自subprocess輸出。這是因爲在其他情況下,Python會拋出第一個值stdout。 得到正常運行的代碼應該是這樣的:

import subprocess  
direct_output = subprocess.check_output('uptime', shell=True) 

這將使你在direct_output變量的正常運行時間。

相關問題