Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Python script to turn off an HDMI-connected monitor on a Raspberry Pi
# This program monitors the screensaver and turns the monitor off
# when the screensaver blanks the screen, and back on again when
# the screensaver unblanks the screen.
import sys # for exit()
import subprocess # for command execution
# command to monitor the screensaver
MONITOR = "xscreensaver-command"
MONITOR_ARGS = [MONITOR, "-watch"]
# commands to turn the screen on and off
CONTROL = "vcgencmd"
CONTROL_BLANK = [CONTROL, "display_power", "0"]
CONTROL_UNBLANK = [CONTROL, "display_power", "1"]
def main():
# start the screen monitoring program, pipe output back to us
prog = subprocess.Popen(MONITOR_ARGS, stdout=subprocess.PIPE)
try: # use try/finally to clean up if an exception occurs
while prog.poll() is None: # subprocess still running
# read a line from the monitoring program, 1 char at a time
line = char = ""
while char != "\n":
line += char
char = prog.stdout.read(1)
# here we have a complete line; check the screensaver op
if line.startswith("BLANK "):
subprocess.call(CONTROL_BLANK)
elif line.startswith("UNBLANK "):
subprocess.call(CONTROL_UNBLANK)
return prog.returncode
finally: # clean up
prog.stdout.close()
prog.kill()
sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment