0

I’ve had a lot of issues regarding the sysfs interface recently, and unfortunately, I’ve got another unrelated one. I’m trying to integrate the sysfs gpio interface into my python3 code. This is because I find sysfs to be a more all rounded module rather than other libraries like gpiod. My code sets up the gpio pin as an output, then drives the line high which in turn causes an led to light up. Here is how I access my code:

sudo python3 ledsysfs

And here is the main code:

import os
os.system('sudo echo 581 > /sys/class/gpio/export')
os.system('sudo echo out >  /sys/class/gpio/gpio581/direction')
os.system('sudo echo 1 >  /sys/class/gpio/gpio581/value')
os.system('sudo echo 581 > /sys/class/gpio/unexport')

The issue with my code is that when I run it, I get an error message that occurs on line 2 and 3:

sh: 1: cannot create /sys/class/gpio/gpio581/direction: Permission denied
sh: 1: cannot create /sys/class/gpio/gpio581/value: Permission denied

I will add that when I run these commands when I'm not in the python script, but rather directly via the command line, it works just fine. Here is what I do through the command line:

sudo echo 581 > /sys/class/gpio/export
sudo echo out >  /sys/class/gpio/gpio581/direction
sudo echo 1 >  /sys/class/gpio/gpio581/value
sudo echo 581 > /sys/class/gpio/unexport

Do you know how I can fix this issue?

Matthew Moller
  • 75
  • 1
  • 12

1 Answers1

0

The privilege escalation (sudo) isn't applied to the shell output redirection (>) because it applies to the command, not to the interpretive shell context it is executed in. Eg., here the command is sudo bar, which produces output, but that output is redirected to bar as the normal user.

sudo foo > bar
^^^^^^^^ 

Why this has been working on the command line for you I can't say, possibly you are logged in root?

Anyway, there are various work-arounds for this, but you don't actually need one.

Here is how I access my code:

sudo python3 ledsysfs

That's sufficient to give the whole process privileges and should apply to processes it spawns (via os.system()), so the sudo in the code is unnecessary (and generally it is a bad idea to hard code things like that).

In this case the more direct route would be to open /sys/class/gpio/export like a file (which it is, albeit a special sort of one) and write to it. This is much less clunky and inefficient than using an os.system() subshell for it.

goldilocks
  • 60,325
  • 17
  • 117
  • 234