How to turn off your Monitor using a Python Script in Ubuntu

The Traditional way of turning your monitor off via hotkey has been broken for a few newer versions. A Python script can bring that functionality back in a reliable and efficient manner.

The older way to turn off hotkey is by using this command:

# xset dpms force off

To Turn off the monitor using a hotkey, you need to have some dependencies, which we have to resolve open up the terminal, and check whether the required package is installed or not?

Check Python

In my case, it is not installed to install these python and Xlib packages open up the terminal and type the following command:

Install python and xlib

It will install the python and python-xlib packages, the next step is to open up text editor (gedit or any other editor of your own choice) 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

Script screenshot

Save your file somewhere, I saved it with the name screen_off.sh, by default it saved under the user’s home directory.

The next step is to allow this file to executable. Go to the properties of that file and click on the check box “Allow Executing file as program” keep all other settings the same and click Close.

File properties

To add a custom shortcut for this file, go to the keyboard layout setting and add a shortcut key, I set Ctrl + 4 you can add of your own choice and click on add appears at the right top corner.

Create shortcut

As you can see that shortcut key has been added or you can execute this file by using simple command ./screen.off.sh.

Make sure these packages have already been installed:

  • sudo apt install gnome-screensaver
  • sudo apt-get install xscreensaver xscreensaver-gl-extra xscreensaver-data-extra

If you want to turn off the monitor using the Shortcut press Ctrl+4 key, it will execute the Script and turn off the monitor.

Turn off monitor shortcut

To directly execute the script using the following command as shown in the figure, it will turn off the monitor.

Run monitor shutdown script

You can also turn off the monitor using the following command:

Command to shutdown the monitor

Conclusion

In this article, you learn how to turn off the Monitor using a bash script with some pre-requisite packages in the Ubuntu Operating System. I hope this article will help you, how to turn off the Monitor Screen?