Search code examples
python-3.xpython-importsudo

Why importing with ipython3 or sudo python3 is different?


I'm trying to use CircuitPython lib but got some troubles, I put the files from the Circuitpython bundle in /lib

  • this works

    $ ipython3
    Python 3.7.3, blabla info
    >> import sys
    >> sys.path.append("/lib/adafruit_hid")
    >> import adafruit_hid
    
  • this works too

    $ python3
    Python 3.7.3, same blabla info
    >> import sys
    >> sys.path.append("/lib/adafruit_hid")
    >> import adafruit_hid
    
  • this doesn't

    $ sudo python3
    Python 3.7.3, same blabla info
    >> import sys
    >> sys.path.append("/lib/adafruit_hid")
    >> import adafruit_hid
    ModuleNotFoundError: No module named 'adafruit_hid'
    

And as the script needs to run as root I'm stuck


Solution

  • I believe this question is related to the one found here:

    https://superuser.com/questions/600349/why-sudo-python-and-python-in-terminal-start-two-different-versions-python/600350

    In essence, it's running different versions of python under sudo. This may mean it cannot run the library correctly.

    Edit:
    This may also be related to Cannot run Python script using sudo. (Try running with the -E flag.)

    By default sudo runs commands in different environment. You can ask sudo to preserve environment with -E switch.

    sudo -E python myScriptName.py
    

    It comes with it's own security risks. So be careful