Search code examples
pythonnetwork-programmingkeyboardpython-idle

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?


Solution

  • Unixy solution using X11/XScreenSaver to get idle time:

    #!/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',        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('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)
    
    print "idle: %d ms" % xssinfo.contents.idle
    
    # cleanup
    xss.XCloseDisplay(display)
    xss.XFree(xssinfo)
    

    (From "X11 idle time and focused window in Python", originally found on thp.io, now apparently only the GitHub gist by the same author survives.)

    A cleanup section was added to the code in a later edit by another user so that it can be called periodically.

    As noted in a comment to the answer they reference, note that you should also do proper return code checking on function calls to avoid ungraceful program termination when X display and other initializations fail for some reason.