How to turn off monitor using Python script in Ubuntu

The traditional way to turn off the monitor with a hotkey has been broken in several new versions. A Python script can return this functionality in a reliable and efficient way.

The old way to disable hotkeys is to use this command:

# xset dpms force off

To turn off the monitor using a hotkey, you need to have some dependencies that we need to resolve by opening a terminal and checking if the required package is installed or not?

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

Install python and xlib

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

Screenshot of the script

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

The next step is to enable execution of this file. Go to the properties of this file and check the box “Allow the file to run as a program”Leave all other settings the same and click Close.

File properties

To add your own shortcut for this file, go to customize your keyboard layout and add a keyboard shortcut, I set Ctrl + 4, you can add as you like, and click Add in the top right corner.

Create shortcut

As you can see this keyboard shortcut has been added, or you can run this file with a simple command ./screen.off.sh

Make sure these packages are already 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 keyboard shortcut Ctrl + 4, it will execute the script and turn off the monitor.

Disable monitor shortcut

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

Run the script to turn off the monitor

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

Command to turn off the monitor

Conclusion

In this article, you will learn how to turn off a monitor using a bash script with some required packages on Ubuntu operating system. Hope this article helps you how to turn off the monitor screen?

How to turn off monitor using Python script in Ubuntu

Sidebar