Writing to /sys/class/backlight/rpi_backlight/brightness is the correct way to change the brightness. Python can write to this file just as it can any other file.
Here’s a quick and dirty library that does just that. Unless you have a remote connection to your Pi, or really know what you’re doing then don’t set the backlight brightness below 20 or turn the power off. It’s not easy to type when you can’t see!
import os
BASE = "/sys/class/backlight/rpi_backlight/"
ON = 0
OFF = 1
def power(state):
if state in (ON,OFF):
_power = open(os.path.join(BASE,"bl_power"), "w")
_power.write(str(state))
_power.close()
return
raise TypeError("Invalid power state")
def brightness(value):
if value > 0 and value < 256:
_brightness = open(os.path.join(BASE,"brightness"), "w")
_brightness.write(str(value))
_brightness.close()
return
raise TypeError("Brightness should be between 0 and 255")