I want to write a Python script that checks whether my device has a display and whether that display is turned on or off.
I googled it, there is a third-party library named "WMI", but it can only get some information like CPU/HDD/process/thread, so I am confused about it.
I am using Windows 10, in case that matters.
Is it possible to get that kind of low level hardware information via Python, and if it is, how can I do it?
解决方案
It looks like Windows does not really have a way to tell you if the monitor is on or off. The WMI Win32_DesktopMonitor class has an 'Availability' property but this doesn't seem to be affected by changing the monitor state. I tested this using the following python script:
import wmi # pip install WMI
import win32gui, win32con
SC_MONITORPOWER = 0xF170
wmic = wmi.WMI()
def powersave():
# Put the monitor to Off.
win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SYSCOMMAND, SC_MONITORPOWER, 2)
# Get the monitor states
print([monitor.Availability for monitor in wmic.Win32_DesktopMonitor()])
if __name__ == '__main__':
powersave()
The SC_MONITORPOWER arguments are documented here.
Unfortunately the result for my monitor is always 3 which means it is "on", even when it is actually powered down either in sleep mode or physically off.
Depending on your requirement, you might just want to send the broadcast message to assert the power state you want and not need to check the current state.