Search code examples
pythonraspberry-piraspbian

Shell Script For Python Throws ModuleNotFoundError


I'm trying to run a python script at start for my Raspberry Pi 3B. My shell script "atboot.sh" looks like this:

#!/bin/bash
cd /home/pi/pythoncodefolder
date >> logs
sudo python3 test.py >> logs

When I try to run it on cmd with sh atboot.sh command, I get an import error which is:

Traceback (most recent call last):
    File "test.py", line 5, in <module>
        import cv2
ModuleNotFoundError: No module named 'cv2'

But when I run the program on cmd without shell script, using python3 test.py, I get no errors.

Thanks.


Solution

  • The use of sudo causing it. When you run python3 program.py you invoke it in your $USER environment setup.

    You can remove Defaults !env_reset from sudoers. Or to add Defaults env_keep += "PYTHONPATH".

    But I would assert that you can do it without sudo in the first place.

    #!/bin/bash
    cd /home/pi/pythoncodefolder
    date >> logs
    python3 test.py >> logs
    

    Also, that's probably a (not exact) duplicate.