#!/usr/bin/python import re import cliapp class AutoDisp(cliapp.Application): lid = 'LVDS1' externals = ['VGA1', 'HDMI1', 'DVI1', 'DP1'] def process_args(self, args): out = self.runcmd(['xrandr', '-q']) outputs = self.parse_outputs(out) got_internal = self.got_output(self.lid, outputs) got_externals = [x for x in self.externals if self.got_output(x, outputs)] argv = ['xrandr'] if got_externals: res, name = max((outputs[x], x) for x in got_externals) argv += ['--output', name, '--mode', '%dx%d' % res] if got_internal: argv += ['--output', self.lid, '--off'] elif got_internal: argv += ['--output', self.lid, '--mode', '%dx%d' % outputs[self.lid]] else: raise cliapp.AppException('Oops, don\'t know what to do') self.runcmd(argv) def got_output(self, name, outputs): return name in outputs def parse_outputs(self, xrandr): output = re.compile(r'^(?P[A-Z0-9]+) connected ') mode = re.compile(r'^ (?P\d+)x(?P\d+) ') result = {} current = None lines = xrandr.splitlines() for line in lines: words = line.split() output_match = output.match(line) mode_match = mode.match(line) if output_match: current = output_match.group('output') elif mode_match: assert current is not None x = int(mode_match.group('x')) y = int(mode_match.group('y')) prev = result.get(current, (0,0)) result[current] = max((x,y), prev) return result AutoDisp().run()