1

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
    sudo leaves only a few variables in the environment. Perhaps you need to copy over PYTHONPATH or similar. – meuh May 15 at 14:33
  • 1
    Interesting. You had to install the module while being logged in as root. Never seen that one before. – Unsigned_Arduino May 15 at 15:33
  • 1
    Just a wag, but based on your Q & the comments, I'd have to guess that something is "out of whack" with your system. Would it be a huge effort to start over with a fresh system? Also, IIRC, sudo changes things in that all of your commands are actually run by exec. – Seamus May 15 at 17:43
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!)

| improve this answer | |
  • 1
    The 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 May 15 at 15:12
  • 1
    Then you should edit your question, probably saying that "I want to run a Python 3 script with root privileges" – Unsigned_Arduino May 15 at 15:29
  • 1
    And, did you try to install the module using pip? (pip3 if you are using Python 3) – Unsigned_Arduino May 15 at 15:30
  • 1
    Yes, first i installed with pip3 as default user which got me the problem and then afterwards i installed with pip3 as root – Phil Noderer May 15 at 15:35
  • 1
    Oh, that makes sense! – Unsigned_Arduino May 15 at 17:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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