-
-
Save iiiGerardoiii/69dab31b7e228f23b1d9bfda075fb353 to your computer and use it in GitHub Desktop.
Python script to turn off an HDMI-connected monitor on a Raspberry Pi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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. | |
# once you put this file in /home/pi/.local/bin/ type: | |
# sudo nano /home/pi/.config/lxsession/LXDE-pi/autostart | |
# and add this line: | |
# @python /home/pi/.local/bin/monitor.py | |
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