使用X11 / XScreenSaver获取空闲时间的Unixy解决方案:
#!/usr/bin/python import ctypes import os class XScreenSaverInfo( ctypes.Structure): """ typedef struct { ... } XScreenSaverInfo; """ _fields_ = [('window',ctypes.c_ulong),# screen saver window ('state',ctypes.c_int),# off,on,disabled ('kind',# blanked,internal,external ('since',# milliseconds ('idle',# milliseconds ('event_mask',ctypes.c_ulong)] # events xlib = ctypes.cdll.LoadLibrary('libX11.so') display = xlib.XOpenDisplay(os.environ['DISPLAY']) xss = ctypes.cdll.LoadLibrary('libXss.so.1') xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo) xssinfo = xss.XScreenSaverAllocInfo() xss.XScreenSaverQueryInfo(display,xlib.XDefaultRootWindow(display),xssinfo) idletime = xssinfo.contents.idle # Cleaning Up xss.XFree(xssinfo) xss.XCloseDisplay(display) print "idle: %d ms" % idletime
(见X11 idle time and focused window in Python.)
编辑@H_502_1@在上面的代码中添加了一个清理部分,以便可以从函数中定期调用它,因为如果没有提供清理,则xDisplay可能会因为未关闭显示而发生错误,因为可以在此link上找到