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:


import time
import subprocess
from Xlib import X
from Xlib.display import Display

display = Display(':0')
root = display.screen().root
        X.ButtonPressMask | X.ButtonReleaseMask | X.PointerMotionMask,
        X.GrabModeAsync, X.GrabModeAsync, 0, 0, X.CurrentTime)
        X.GrabModeAsync, X.GrabModeAsync, X.CurrentTime)'xset dpms force off'.split())
p = subprocess.Popen('gnome-screensaver-command -i'.split())

while True:
    print display.next_event()

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

Next, right-click the file and go to 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.

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.