1. Andy Mikhailenko
  2. scripts


scripts / auto-xrandr.py

#!/usr/bin/env python

Checks how many monitors are connected and executes the corresponding command.
The commands are meant to be simple shell scripts that call xrandr with certain
arguments. This script does not attempt to replace those scripts because it's
impossible to guess how the monitors are physically aligned. Try krandr,
grandr, arandr or a similar GUI program to generate the script. For me arandr
worked best.

2010 (c) Andrey Mikhaylenko

import re
from subprocess import Popen, PIPE, call

SINGLE_HEAD_COMMAND = 'screenlayout-single'
#"xrandr --output LVDS1 --mode 1280x800 --pos 0x0 --rotate normal --output TV1 --off --output VGA1 --off"

DUAL_HEAD_COMMAND = 'screenlayout-dual'
#"xrandr --output LVDS1 --mode 1280x800 --pos 1280x0 --rotate normal --output TV1 --off --output VGA1 --mode 1280x1024 --pos 0x0 --rotate normal"

device_re = re.compile(r'^(VGA|LVDS)\d+')

def get_monitors():
    process = Popen(['xrandr'], stdout=PIPE)
    results = process.communicate()
    data = results[0]
    lines = data.split('\n')
    definitions = (line for line in lines if device_re.match(line))
    monitors = (d.split(' ')[:2] for d in definitions)
    return (dict(zip(('name','state'), mon)) for mon in monitors)

def get_connected_monitors():
    monitors = get_monitors()
    return (m for m in monitors if m['state'] == 'connected')

if __name__=='__main__':
    connected_cnt = len(list(get_connected_monitors()))
    if 1 < connected_cnt:
        print('Activating dual head (you have %d monitors connected)...' %
        print('Using single monitor...')