0

我正在尝试在我的 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)。谢谢!

4

3 回答 3

2

我现在看不出有什么问题,但如果它有助于我工作的机器人做了类似的事情,也许你可以看看那里:

uptime() 在https://bazaar.launchpad.net/~p1tr-dev/p1tr/main/view/head:/plugins/info.py使用定义在https://bazaar.launchpad.net/~p1tr- 的 _get_output dev/p1tr/main/view/head:/lib/plugin.py

于 2012-12-30T12:49:01.733 回答
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
于 2012-12-30T16:12:12.857 回答
0

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

于 2012-12-30T15:53:09.077 回答