2016-12-14 47 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变量的正常运行时间。