#RaspberryPi – Running a #python script in a Python Virtual Environment on reboot / startup

Hi!

Adrian Rosebrock is a very smart person who has tons of great resources about Computer Vision in PyImageSearch.com. Most of them are with Python, and he also have some of them focused on how to perform CV using OpenCV in a Raspberry Pi.

In the post [Running a Python + OpenCV script on reboot, see resources] he explains how to automatically run a Python script when a Raspberry Pi starts. He uses python virtual environments, so the first 2 commands are focused on to load the virtual env. Then, move to the app folder and run the python script.

source ~/.profile
workon cv
cd /home/pi/pi-face-recognition
python startup.py

Something like this:

python source and cv on raspberry pi.

The suggested approach consists on create a Schell Script [.sh file] with these lines and add them to the auto start. However, once you create the file and test it, there seems to be an issue with the Source command.

python source not working on SH file

Ok, so no source command in an SH file. I started to think on install all my python dependencies directly in the main user, however the idea of working with virtual environments is very useful for me. It was to read online about Linux, python and more.

Note: Before moving forward, I may need to add some context. I need to run my python script in a Terminal. My device will always auto-start with a 3.5 inches touch screen and a camera, so I need some GUI loaded.

This is an excellent article on how to add actions to the Raspberry Pi start-up [How to Execute a Script at Startup on the Raspberry Pi, see resources]. So I added my SH file here and it didn’t work and I need to figure out how to load a virtual environment and run a python script.

After a couple of tests, I realized that all the files I need are part of the virtual env location in the device.

raspberry pi python folder for virtual envs

So, I only need to add the full path to my command to make it work without the and [workon] command. My complete command will became:

/home/pi/.virtualenvs/cv/bin/python /home/pi/pi-face-recognition/startup.py

So, I edited my autostart file adding this command

raspberry pi auto start file launching python script with a virtual env

And done! My python script running on a python virtual environment on the device startup is working!

Happy coding!

Greetings @ Toronto

El Bruno

Resources

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.