Skip to content

Instantly share code, notes, and snippets.

Created January 5, 2020 19:00
What would you like to do?
#!/usr/bin/env python3
import os, sys, re, time, signal, subprocess as sp
tvs = '/opt/vc/bin/tvservice'
def get_hdmi_res():
# state 0x120006 [DVI DMT (82) RGB full 16:9], 1920x1080 @ 60.00Hz, progressive
# state 0x40001 [NTSC 4:3], 720x480 @ 60.00Hz, interlaced
proc =[tvs, '-s'], check=True, stdout=sp.PIPE)
mode = proc.stdout.decode().strip()
print(f'Display mode: {mode}')
m =
r'^state (?P0x[\da-fA-F]+) \[(?P[^\]]+)\].*?'
r'\s+(?P\d+)x(?P\d+)\s+@\s+(?P[\d.]+)Hz\b', mode )
if not m: return
if 'NTSC' in'm'): return
return int('w')), int('h'))
def main():
import argparse
parser = argparse.ArgumentParser(
description='Script to wait until HDMI display is plugged-in and configured.')
opts = parser.parse_args(sys.argv[1:])
signal.signal(signal.SIGINT, lambda *s: sys.exit())
ev, mon = None, sp.Popen( [tvs, '-M'],
stdout=sp.PIPE, stderr=sp.STDOUT )
while True:
res = get_hdmi_res()
if res:
if ev is None: return # everything already setup
ev = mon.stdout.readline().decode().strip()
print(f'Display event: {ev}')
time.sleep(0.5) # trivial debounce
if 'HDMI is attached' in ev:[tvs, '--preferred'])
time.sleep(0.5) # to let display catch-up, if necessary
# elif 'HDMI cable is unplugged' in ev:[tvs, '--off'])
try: mon.wait(2)
except sp.TimeoutExpired: mon.kill()
w, h = res
time.sleep(1) # just in case
print(f'Resizing framebuffer to {w}x{h}')'fbset -xres {w} -yres {h}'.split(), check=True)
mode =['fbset'], stdout=sp.PIPE, check=True)
if __name__ == '__main__': sys.exit(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment