I'm not sure if this issue belongs here or on the python side, but hopefully someone can help me on this, and others can benefit here as well.

I've managed to customize the commands found in this discussion, combining knowledge from this question about echoing sudo, and managed to get

echo 1 | sudo tee /sys/class/backlight/rpi_backlight/bl_power > /dev/null
echo 0 | sudo tee /sys/class/backlight/rpi_backlight/bl_power > /dev/null

as a working command-line entry to turn the backlight on and off from the pi user account.

sudo sh -c "echo 1 > /sys/class/backlight/rpi_backlight/bl_power"
sudo sh -c "echo 0 > /sys/class/backlight/rpi_backlight/bl_power"

worked equally well.

Now, combining a subprocess.Popen() method in python (referring to this page), I've tried

def screen_off():
    command  = "echo 1 | /usr/bin/sudo tee /sys/class/backlight/rpi_backlight/bl_power"
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    output = process.communicate()[0]


def screen_off():
    commandarr = ["/usr/bin/sudo","/bin/sh","-c","\"echo 1 > /sys/class/backlight/rpi_backlight/bl_power\""]
    process = subprocess.Popen(commandarr, stdout=subprocess.PIPE)
    output = process.communicate()[0]

to no avail; the former prints

b'1 | /usr/bin/sudo tee /sys/class/backlight/rpi_backlight/bl_power\n'

and the latter

/bin/sh: 1: echo 1 > /sys/class/backlight/rpi_backlight/bl_power: not found

the latter using the split() method gives

1: 1: 1: Syntax error: Unterminated quoted string

The shutdown counterpart works OK, so it probably isn't a user privilege issue...
The former is probably a problem using the pipe method, and the latter a problem with quotes and/or the sh -c parameter not going through...

Is there any way around these problems, or would I be better off writing a shell script and calling that instead?

1 Answer 1


I think I've managed to find a solution for the former method.
The problem was with trying to use pipes within one process call, so I referred to this answer and used two process calls and piped them together:

def screen_off():
    command1 = "echo 1"
    command2 = "/usr/bin/sudo tee /sys/class/backlight/rpi_backlight/bl_power"
    process1 = subprocess.Popen(command1.split(), stdout=subprocess.PIPE)
    process2 = subprocess.Popen(command2.split(), stdin=process1.stdout, stdout=subprocess.PIPE)
    output = process2.communicate()[0]

to get the screen to turn off properly...!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.