Python – Control Screen with Python

controlskeyboard-shortcutspythonscreen

is there a way to control the screen/monitor with python, like for example turn it off an on again (comparable to the shortcut-buttons on laptop keyboards)?

Thank you!

Best Solution

Most modern laptops have a physical connection between the button and the monitor. For instance, my Dell precision i can boot the PC and dimm my display even before BIOS launches which tells me, it's wired via hardware connections.

With that sad, i can still emulate a few system-calls from within the OS to execute the task as well, not just as energy efficient as pressing the actual button.

Doing this requires you to (on windows) use pywin32 to connect to the appropriate system api's and execute a very specific command to do so, and it is tricky if you're not familar with System API's and calling the windows 32 functions.

Something along the lines of:

import os, win32com.client

def runScreensaver():
    strComputer = "."
    objWMIService = win32com.client.Dispatch("WbemScripting.SWbemLocator")
    objSWbemServices = objWMIService.ConnectServer(strComputer,"root\cimv2")
    colItems = objSWbemServices.ExecQuery("Select * from Win32_Desktop")
    for objItem in colItems:
        if objItem.ScreenSaverExecutable:
            os.system(objItem.ScreenSaverExecutable + " /start")
            break

If you're on linux you can try to just execute os.system() one of the following: