Create a gist now

Instantly share code, notes, and snippets.

@bfroehle /xres.py
Last active Dec 16, 2015

What would you like to do?
A script to change the screen resolution and restart Nautilus.
#!/usr/bin/env python
"""
Change the screen resolution and restart Nautilus.
You may need to provide your VNC server with a list of available
resolutions. See:
http://stackoverflow.com/questions/15816/changing-the-resolution-of-a-vnc-session-in-linux
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 Bradley Froehle <brad.froehle@gmail.com>
# Distributed under the terms of the BSD License.
#-----------------------------------------------------------------------------
import argparse
import os
import subprocess
import sys
import time
#def resolution(r):
# # r = computers.get(r, r)
# if r not in available_resolutions():
# msg = "%r is not a valid resolution." % r
# raise argparse.ArgumentTypeError(msg)
# return r
# Fill this in with the preferred screen resolutions of your various devices.
computers = {
'ipad': '1024x700',
'laptop': '1280x800',
'desktop': '1680x1050',
}
def run_xrandr():
"""Call xrandr and return list of available resolutions."""
lines = subprocess.check_output(['xrandr']).splitlines()
resolutions = []
current = 'unknown'
for line in lines[1:]:
if line[0] not in (' ', '*'):
continue
r = line.split()[1:4]
if r[1] != 'x':
continue
resolutions.append(''.join(r))
if line[0] == '*':
current = ''.join(r)
return resolutions, current
avail, current = run_xrandr()
parser = argparse.ArgumentParser(
description='View or change screen resolution',
)
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument(
'resolution',
metavar="resolution",
choices=avail + computers.keys(),
nargs='?',
help="Screen resolution (as '<width>x<height>') or computer name.",
)
group.add_argument(
'-l',
'--list',
action='store_true',
help="List available resolutions.",
)
def restart_nautilus():
"""Kill and restart nautilus."""
with open(os.devnull, 'w') as devnull:
subprocess.check_call(['nautilus', '-q'],
stdout=devnull, stderr=devnull)
time.sleep(1)
subprocess.Popen(['nautilus', '-n'],
stdout=devnull, stderr=devnull)
if __name__ == "__main__":
args = parser.parse_args()
if args.list:
print("Available resolutions:")
for a in avail:
print(" %s %s" % ('*' if a == current else '-', a))
print("Known computers:")
for c, a in computers.items():
print(" %s %s (%s)" % ('*' if a == current else '-', c, a))
if args.resolution:
r = args.resolution
r = computers.get(r, r)
subprocess.check_call(['xrandr', '-s', r])
restart_nautilus()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment