Wednesday, November 17, 2021

[SOLVED] Unable to access packages inside virtual environment on startup

Issue

I am working on creating a bash file on my raspberry pi in order to be able to launch a webapp project that I have made when the raspberry pi starts up. I have been able to figure out most of it, except for I have issues with the virtual environment letting me access my packages that were installed in the virtual environment. When I run

workon tm
python main.py

in the terminal I am able to get my project working fine. But when I run my bash file

#!/bin/bash
# startup.sh
#Open Chromium on the Raspberry Pi on fullscreen on bootup. Then open the virtual environemnt, and then run our python script

#su - pi -c "/usr/bin/chromium-browser --start-fullscreen 127.0.0.1:5000"
cd /
cd /home/pi/MySQLAppTrueTrue 
source /usr/local/bin/virtualenvwrapper.sh
source ~/.bashrc
#workon /home/pi/.virtualenvs/tm
workon tm
sudo python /home/pi/MySQLAppTrueTrue/main.py

I get the error

pi@raspberrypi:~/MySQLAppTrueTrue $ ./startup.sh
Traceback (most recent call last):
  File "/home/pi/MySQLAppTrueTrue/main.py", line 1, in <module>
    from webapp import app #import the web app
  File "/home/pi/MySQLAppTrueTrue/webapp/__init__.py", line 2, in <module>
    from flask_mysqldb import MySQL #import mySQL
ImportError: No module named flask_mysqldb

Does this mean that my workon tm line isnt actually causing the device to be working on the virtual environment. If so how do I get that to work? Or do I just need to install my packages globally instead of in the virtual environment?


Solution

Instead of all that virtualenvwrapper workon magic, you should probably just use that virtualenv's Python interpreter:

#!/bin/bash
cd /home/pi/MySQLAppTrueTrue 
sudo /home/pi/.virtualenvs/tm/bin/python /home/pi/MySQLAppTrueTrue/main.py


Answered By - AKX