I have a Raspberry Pi with Raspbian Buster Lite which I start in KIOSK mode with autologin. The purpose is to display a single web page on the connected 7" touchscreen (with Chromium). If the system is idle, my python script should detect it and dim the screen automatically. When a user interacts with the screen again, it should light up.
This is my script (dim_screen.py):
#!/usr/bin/env python3
import subprocess
import time
import sys
from rpi_backlight import Backlight
backlight = Backlight()
# read arguments from the run command:
# idle time before dim (in seconds)
idleTimeBeforeDimMS = int( sys.argv[1] )*1000
# brightness when dimmed (between 0 and 100)
brightnessDimmed = int( sys.argv[2] )
brightnessFull = 100
def get(cmd):
# just a helper function
return subprocess.check_output(cmd).decode("utf-8").strip()
isIdle0 = False
stateChanged = False
timeIntervalToWatchChangesS = 100 / 1000
while True:
time.sleep( timeIntervalToWatchChangesS )
currentIdleTimeMS = int( get("xprintidle") )
isIdle = currentIdleTimeMS > idleTimeBeforeDimMS
stateChanged = isIdle0 != isIdle
if isIdle and stateChanged:
# idling
backlight.brightness = brightnessDimmed
elif not isIdle and stateChanged:
# active
backlight.brightness = brightnessFull
# set current state as initial one for the next loop cycle
isIdle0 = isIdle
My script works as expected when I start it from a SSH (I can test it by connecting to my Pi from Putty on a Windows 10 computer):
pi@raspberrypi:~$ /usr/bin/python3 /home/pi/startup_scripts/dim_screen.py 10 25
Unfortunately this is not the case when I try to run the script as a service on boot from systemd (or via systemctl start dim_screen.service). I can't get it to work.
This is my dim_screen.service file:
[Unit] Description=Ensures that the 7" raspberry pi screen automatically will dim to 10% brightness after 25 minutes of user not interacting with it After=multi-user.target [Service] ExecStart=/usr/bin/python3 /home/pi/startup_scripts/dim_screen.py 10 25 [Install] WantedBy=multi-user.target
If I do a reboot and run sudo systemctl status dim_screen.service, I get this:
I believe that the most important debug info is this line: Command 'xprintidle' returned non-zero exit status 1.
That's strange I think? Here is what happens if I run xprintidle in the terminal:
pi@raspberrypi:~$ xprintidle 11399922
In other words, I get a valid response from xprintidle. I believe there is something else that I do not understand?
What is the correct way to start my python script (dim_screen.py) as a service?

xprintidledoesn't have access to the X server, and doesn't have$DISPLAYdefined.xprintidleis accessible from my terminal?