Python IRC bot系统正常运行时间

时间:2012-12-30 09:27:23

标签: python bots irc

我正在尝试在我的irc机器人中显示系统正常运行时间。我正在使用的脚本是:

   #linux
import os, sys
from datetime import timedelta
from util import hook
import subprocess
import datetime
@hook.command
def uptime_linux(inp,say=None):
    with open('/proc/uptime', 'r') as f:
        uptime_seconds = float(f.readline().split()[0])
        uptime_string = str(timedelta(seconds = uptime_seconds))
        say(uptime_string)
# windows

def uptime():
    """Returns a datetime.timedelta instance representing the uptime in a Windows    2000/NT/XP machine"""
    if not sys.platform.startswith('win'):
        raise RuntimeError, "This function is to be used in windows only"
    cmd = "net statistics server"
    p = subprocess.Popen(cmd, shell=True, 
          stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    (child_stdin, child_stdout) = (p.stdin, p.stdout)
    lines = child_stdout.readlines()
    child_stdin.close()
    child_stdout.close()
    lines = [line.strip() for line in lines if line.strip()]
    date, time, ampm = lines[1].split()[2:5]
    #print date, time, ampm
    m, d, y = [int(v) for v in date.split('/')]
    H, M = [int(v) for v in time.split(':')]
    if ampm.lower() == 'pm':
        H += 12
    now = datetime.datetime.now()
    then = datetime.datetime(y, m, d, H, M)
    diff = now - then
    return diff

@hook.command
def uptime_win(inp,say=None):
    if __name__ == '__main__':
        say(uptime())

它没有给我一个错误,但它没有显示。我看了代码,我不明白为什么我无法看到它。也许它可能有点小但我看不到它:D。我有所需的模块,它仍然不起作用:'(。另外我想问你们是否有更容易的方法来获得Windows的正常运行时间(我已经为linux了)。谢谢!

3 个答案:

答案 0 :(得分:2)

我现在没有看到什么是错的,但是如果它帮助我工作的机器人做了类似的事情,也许你可以看看那里:

正常运行时间()https://bazaar.launchpad.net/~p1tr-dev/p1tr/main/view/head:/plugins/info.py 使用https://bazaar.launchpad.net/~p1tr-dev/p1tr/main/view/head:/lib/plugin.py

中定义的_get_output

答案 1 :(得分:0)

我认为您不在主模块中,因此您必须删除if __name__ == '__main__':

答案 2 :(得分:0)

没有在Windows上测试,因为我没有方便的Windows框,而是使用psutil(应该是跨平台的)

>>> pid = psutil.Process(1) # get main process (kernel or close to it)
>>> pid
<psutil.Process(pid=1, name='init') at 31222480>
>>> pid.create_time # create_time is effectively system up time (or should be close to it)
1356597946.03