Testing for Inactivity in Python on Mac
Is there a way to test, using Python, how long the system has been idle on Mac? Or, failing that, even if the system is currently idle?
Answer
Using the information from the accepted soluti开发者_如何转开发on, here is an ugly but functional and fairly efficient function for the job:
from subprocess import *
def idleTime():
'''Return idle time in seconds'''
# Get the output from
# ioreg -c IOHIDSystem
s = Popen(["ioreg", "-c", "IOHIDSystem"], stdout=PIPE).communicate()[0]
lines = s.split('\n')
raw_line = ''
for line in lines:
if line.find('HIDIdleTime') > 0:
raw_line = line
break
nano_seconds = long(raw_line.split('=')[-1])
seconds = nano_seconds/10**9
return seconds
Untested (for now), but according to this thread you could parse the output of
ioreg -c IOHIDSystem
精彩评论