Joseph Turian Joseph Turian - 1 month ago 7x
Python Question

In Python on Unix, determine if I am using my computer? or idle?

I would like to write a script to do an heavy network upload, in the background.
However, I would like it to pause when I am using my computer (either by detecting network activity or keyboard activity or that I am not idle).

What is the best way to detect that I am using the computer, on Python on Unix?


Unixy solution using X11/XScreenSaver to get idle time:

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',        ctypes.c_int),   # blanked,internal,external
              ('since',       ctypes.c_ulong), # milliseconds
              ('idle',        ctypes.c_ulong), # milliseconds
              ('event_mask',  ctypes.c_ulong)] # events

xlib = ctypes.cdll.LoadLibrary('')
display = xlib.XOpenDisplay(os.environ['DISPLAY'])
xss = ctypes.cdll.LoadLibrary('')
xss.XScreenSaverAllocInfo.restype = ctypes.POINTER(XScreenSaverInfo)
xssinfo = xss.XScreenSaverAllocInfo()
xss.XScreenSaverQueryInfo(display, xlib.XDefaultRootWindow(display), xssinfo)

# Cleaning Up

print "idle: %d ms" % xssinfo.contents.idle

(See X11 idle time and focused window in Python.)

Edit A cleaning up section added in the code above so that it can be periodically called from a function, because if no cleaning is supplied then an error may occur on the xDisplay due to not closed display as can be found on this link