cycle_xrandr.py : dual and single displays on Ubuntu

July 10, 2008 at 06:24 AM | categories: python, linux | View Comments

Linux power management has gotten good recently. My last two laptops (HP dv9000 and Macbook Pro) have supported hardware suspend mode out of the box. I'm impressed!

Being that I hardly ever turn off the laptop (I just suspend now) I'm left with an annoyance: I use two displays at work and one everywhere else. In Ubuntu, I was easily able to setup dual and single modes such that when I boot up, Xorg detects how many displays are connected appropriately. But now that I don't turn off the machine, I want to be able to just plug in another monitor and go. I don't want to have to reboot the computer. I don't even want to have to log out. I want to plug the monitor in, leave all my apps running and in the state they are in.

Xrandr does this and it works great. But what if I'm in dual display mode but I only actually have one monitor connected? Can I get to an open terminal to use xrandr? Easily? Probably not.

I wrote the following python script to take care of this. It detects all of the modes that xrandr knows about and cycles to the next size listed. I then bind this script to a custom keyboard shortcut so I don't have to type or even see anything on the screen:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = "Ryan McGuire (ryan@enigmacurry.com)"
__date__   = "Thu Jul 10 15:27:18 2008"

"""Cycle through all screen resolutions detected by xrandr"""

from subprocess import Popen, PIPE
import re

size_re = re.compile("^   ([0-9]*x[0-9]*)\W*[0-9]*\.[0-9]*(\*)?")

def list_sizes():
    """List all sizes detected by xrandr,
    ordered by the next resolution to cycle to"""
    p1 = Popen(['xrandr'], stdout=PIPE)
    sizes = []
    current_size_index = 0
    for line in  p1.communicate()[0].split("\n"):
        m = size_re.match(line)
        if m:
            sizes.append(m.group(1))
            if m.group(2) == "*":
                current_size_index = len(sizes) - 1
    return sizes[current_size_index+1:] + sizes[:current_size_index+1]

if __name__ == '__main__':
    Popen(['xrandr','-s',list_sizes()[0]])
Read and Post Comments