Jasar Orion
Jasar Orion

Reputation: 332

Python get idle duration on Linux

I'm making a script that gets the idle duration based on the last mouse or keyboard input time. The following piece of code worked on Windows but I need one which would run on Linux.

class LASTINPUTINFO(Structure):
    _fields_ = [
        ('cbSize', c_uint),
        ('dwTime', c_uint),
    ]

def get_idle_duration():
    # get idle time
    lastInputInfo = LASTINPUTINFO()
    lastInputInfo.cbSize = sizeof(lastInputInfo)
    windll.user32.GetLastInputInfo(byref(lastInputInfo))
    millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
    return millis / 1000.0

print(get_idle_duration())

Can someone help me run this on both Windows and Linux?

Upvotes: 2

Views: 855

Answers (1)

mtm
mtm

Reputation: 512

You can refer idle.py by Gajim

Just call the getIdleSec() to get the idle time in seconds.

If you execute idle.py, it will wait for 2.1 seconds and then print the idle time. Later it frees the held data after which if you call the function, it will return zero.

The problem with the code given in the question is that it uses windll which is specific to Windows.

If you want to see the script in action in a more detailed manner, you can change main as follows:

if __name__ == '__main__':
    import time
    for i in range(0,10):
        print(getIdleSec())
    close()

This works on Ubuntu and should work on all Debian based operating systems.

Upvotes: 2

Related Questions