I'm trying to use the RPi.GPIO Library in a python-script with root-privileges. I essentially need to run it with sudo because other stuff in my script require root-privileges.
When i try the following code without sudo, everything works fine:
import RPi.GPIO as GPIO
But as soon as i try to run it with sudo, im getting the following error:
ModuleNotFoundError: No module named 'RPi'
I have tested the rest of my script, it is working fine without the GPIO-Controlling. What i find especially interesting is that seemingly every other post is about getting GPIO to run without root privileges, and im trying to achieve the opposite and couldnt find any information about it.
EDIT:
The suggested Installation process for the Module via pip3 was already successfully done before i ran into this problem. I have tested other scripts using the module and running without sudo, works perfectly fine.
SOLUTION:
i reinstalled the Module while beeing logged in as root.
1 Answer 1
If the script already has root privileges, then why would you need to run it with sudo
?
At the terminal, launch Python 3 using sudo
and try this:
$ sudo python3
>>> import RPi.GPIO as GPIO
If it still says ModuleNotFoundError
, than install it using:
pip3 install RPi.GPIO
Make sure in your current directory that the script is in, that no files are named after modules. (Like, don't name a file in your current working directory RPi.py
otherwise Python will think that's the module!)
-
1The script itself doesn't have root-privileges. I'm just trying to run the script as sudo but as soon as i do that the Module can't be found.Phil Noderer– Phil Noderer2020年05月15日 15:12:54 +00:00Commented May 15, 2020 at 15:12
-
1Then you should edit your question, probably saying that "I want to run a Python 3 script with root privileges"Unsigned_Arduino– Unsigned_Arduino2020年05月15日 15:29:39 +00:00Commented May 15, 2020 at 15:29
-
1And, did you try to install the module using
pip
? (pip3
if you are using Python 3)Unsigned_Arduino– Unsigned_Arduino2020年05月15日 15:30:27 +00:00Commented May 15, 2020 at 15:30 -
1Yes, first i installed with pip3 as default user which got me the problem and then afterwards i installed with pip3 as rootPhil Noderer– Phil Noderer2020年05月15日 15:35:24 +00:00Commented May 15, 2020 at 15:35
-
1Oh, that makes sense!Unsigned_Arduino– Unsigned_Arduino2020年05月15日 17:52:20 +00:00Commented May 15, 2020 at 17:52
sudo
leaves only a few variables in the environment. Perhaps you need to copy over PYTHONPATH or similar.sudo
changes things in that all of your commands are actually run byexec
.