在Mac上用Python检测不活动状态

9 投票
1 回答
983 浏览
提问于 2025-04-15 20:18

有没有办法用Python来测试一下Mac系统闲置了多久?或者,如果不行的话,能不能知道系统现在是否处于闲置状态?

回答

根据被接受的解决方案,这里有一个虽然看起来不太好但能正常工作且效率还不错的函数:

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

1 个回答

2

目前还没有测试过,不过根据这个讨论帖,你可以分析一下下面这个命令的输出:

ioreg -c IOHIDSystem

撰写回答