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 solution, 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
Your best way to get started with Python on macOS is through the IDLE integrated development environment, see section The IDE and use the Help menu when the IDE is running. If you want to run Python scripts from the Terminal window command line or from the Finder you first need an editor to create your script.
A File Editor Every programmer needs to be able to edit and save text files. Python programs are files with the . py extension that contain lines of Python code. Python IDLE gives you the ability to create and edit these files with ease.
Call get_idle_duration() to get idle time in seconds.
Untested (for now), but according to this thread you could parse the output of
ioreg -c IOHIDSystem
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With