The traditional way of turning your monitor off via a hotkey has been broken for a few versions now. A pretty simple Python script can bring that functionality back reliably and efficiently.

The old way of turning off you monitor was through the xset command:

xset dpms force off

There are a few variations on that, but since Ubuntu Karmic (9.10), it’s been broken. Some of the system calls apparently don’t get along well with this command, causing the screen to wake up after about a minute. After being annoyed at this for quite some time, I found a few solutions on the Ubuntu Forums. Running this command in a loop seems CPU intensive, and there isn’t a very elegant way to escape it. Thankfully, one user, nxmehta, found a solution utilizing a simple Python script, and it works on everything from Karmic to Natty.

First of all, you need to have a few dependencies, so open up a terminal and enter the following command:

sudo apt-get install python python-xlib

This will install the python and python-xlib packages if they aren’t installed already. Next, open up Text Editor (gedit) and copy/paste the following text:

#!/usr/bin/python

import time

import subprocess

from Xlib import X

from Xlib.display import Display

display = Display(':0')

root = display.screen().root

root.grab_pointer(True,

X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,

X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime)

root.grab_keyboard(True,

X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)

subprocess.call('xset dpms force off'.split())

p = subprocess.Popen('gnome-screensaver-command -i'.split())

time.sleep(1)

while True:

print display.next_event()

p.terminate()

break

gedit

Save your file somewhere with a proper name. I stuck mine in ~/bin/screen_off.sh with the rest of my scripts.

Next, right-click the file and go to Properties.

properties

Under the Permissions tab, be sure “Allow executing file as program” is checked. Click Close.

Now you can assign it to any keyboard shortcut! I like to set mine to Caps Lock, so I had to disable that key first. You can do that by going to Keyboard > Layouts > Options.

keyboard layout options

Here, choose “Caps Lock is disabled” under Caps Lock key behavior.

To assign this script to a keyboard shortcut, open up Keyboard Shortcuts preferences.

shortcuts

Click Add, give the shortcut a name, and the command will just be the location of the script. Click Apply, then click under shortcut to set it. If you disabled Caps Lock, you’ll see it listed as “VoidSymbol” but it will work without a hitch.

This has been bugging me for quite some time, and the solution was a bit tough to find what with all of the complaints floating around. Hopefully this will help you conserve your laptop battery.