I am trying to invoke a bash command from my python application in order to change background light on my touch screen. The python application will run on my Raspberry Pi (Rasbian/stretch).
It's not complicated to run the bash command in a terminal: sudo sh -c "echo 80 > /sys/class/backlight/rpi_backlight/brightness"
will certainly dim the screen (which is what I want). But how can I sudo
scripts in my python application? (I know that there are several threads talking about this, for example this Using sudo with Python script, but I do not understand how to do it in practice?)
This is my code:
#!/usr/bin/env python3
import subprocess
import time
import sys
# read arguments from the run command:
# idle time before dim (in seconds)
idleTimeBeforeDimMS = int( sys.argv[1] )*1000
# brightness when dimmed (between 0 and 255)
brightnessDimmed = int( sys.argv[2] )
brightnessFull = 255
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
bashCommand = "echo 50 > /sys/class/backlight/rpi_backlight/brightness"
subprocess.run(['bash', '-c', bashCommand])
elif not isIdle and stateChanged:
# active
bashCommand = "echo 255 > /sys/class/backlight/rpi_backlight/brightness"
subprocess.run(['bash', '-c', bashCommand])
# set current state as initial one for the next loop cycle
isIdle0 = isIdle
If I run the script right out of box, I get an error with my bash command: bash: /sys/class/backlight/rpi_backlight/brightness: Permission denied
. That's ok, I understand that I am missing the sudo
-part, but where should I put it?