I have a Mac Mini that is connected to a single, external display via HDMI. It is a third-party display (made by Dell); the "change brightness" function keys on the Apple keyboard have no effect the display.
The display ON/OFF state is toggled simply by manually pressing the power button on the face of the display.
I am looking for Python code that checks whether this display is ON or OFF. I am open to a command-line-based solution.
Note that the display remains connected to the computer whether the display is ON or OFF. Consequently, the Display Manager library cannot help me here.
The context is that I want a Python script to only play some audio when the display is turned OFF.
According to this SO post you can check the specifications of attached monitors on MacOS with the following command:
$ system_profiler SPDisplaysDataType
This will return information such as :
Graphics/Displays:
NVIDIA GeForce GT 640M:
Chipset Model: NVIDIA GeForce GT 640M
Type: GPU
Bus: PCIe
PCIe Lane Width: x16
VRAM (Total): 512 MB
Vendor: NVIDIA (0x10de)
Device ID: 0x0fd8
Revision ID: 0x00a2
ROM Revision: 3707
Displays:
iMac:
Display Type: LCD
Resolution: 1920 x 1080
Pixel Depth: 32-Bit Color (ARGB8888)
Main Display: Yes
Mirror: Off
Online: Yes
Built-In: Yes
Connection Type: DisplayPort
My assumption is that when no display is connected, there will be no strings for Display Type
, Resolution
or the others.
Here is more info on running a command line program in Python with command line arguments, and receiving the output, i.e. :
>>> import subprocess
>>> result = subprocess.run(['system_profiler', 'SPDisplaysDataType'], stdout=subprocess.PIPE)
>>> result.stdout
And result.stdout will contain the string returned (something like shown previously). Then you can search the returned string for which ever parameters you want maybe:
if "Display Type" not in result.stdout:
screenConnected = false
playMusic()
Obviously its worth checking other parameters and adding some error handling, but maybe this is a place to start.
I'm not sure if there could be a callback approach to this / haven't found any Python libraries myself, but please comment any in my answer and I will update.
Let me know if this works!