Skip to content
Advertisement

How to check whether screen is off in Mac/Python?

How do I check whether the screen is off due to the Energy Saver settings in System Preferences under Mac/Python?

Advertisement

Answer

Quick and dirty solution: call ioreg and parse the output.

import subprocess
import re

POWER_MGMT_RE = re.compile(r'IOPowerManagement.*{(.*)}')

def display_status():
    output = subprocess.check_output(
        'ioreg -w 0 -c IODisplayWrangler -r IODisplayWrangler'.split())
    status = POWER_MGMT_RE.search(output).group(1)
    return dict((k[1:-1], v) for (k, v) in (x.split('=') for x in
                                            status.split(',')))

In my computer, the value for CurrentPowerState is 4 when the screen is on and 1 when the screen is off.

Better solution: use ctypes to get that information directly from IOKit.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement