Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

macos

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

like image 967
ceiling cat Avatar asked Jan 10 '13 07:01

ceiling cat


1 Answers

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.

like image 182
Martin Blech Avatar answered Sep 18 '22 00:09

Martin Blech