【发布时间】:2012-12-31 00:12:12
【问题描述】:
我正在尝试在我的 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 的)。谢谢!
【问题讨论】:
-
你试过不给两个函数同名吗?
-
是的,实际上第二个 def uptime() 在我的代码中有其他定义,我只是在这里更改了它。它是 uptime_win,但我仍然不知道为什么当我执行 .uptime_win 时它不起作用。我试过做 .uptime_win 1,但又一次,不知道大声笑。我用新定义编辑了我的第一篇文章。
-
好吧,你仍然需要以某种方式调用该函数。
if __name__ == '__main__'在这里的函数内部,所以uptime_win不会神奇地调用自己。也许您打算将此if放在模块级别? -
很遗憾没有。你应该做一些调试:确保函数被实际调用,在中间添加一些诊断
prints。