Managing Python Virtual Environments
Jun 19, 2023
Clean and neat Python virtual environments on Raspberry Pi thanks to the virtualenvwrapper.
Jul 1, 2023 06:16 PM
Python environments can get complex and problematic without virtual environments. We can use venv module that comes built-in with Python to manage it, but it may get complex too after a while. For these needs specifically, virtualenvwrapper has been developed.
Install virtualenvwrapper with pip
sudo pip3 install virtualenvwrapper
Virtualenvwrapper uses a sh file to initialize all the commands that we are going to use. In order to make it executable at the beginning of all sessions, we are going to add it to the .bashrc
But first, we need to know where it is. To check the location of the
virtualenvwrapper.sh, run the command below.
Output on my system is as follows.
In order to add it to the
.bashrcrun the following commands, do not forget to replace the location if it is different.
echo 'export VIRTUALENVWRAPPER_PYTHON=/usr/bin/python3' >>~/.bashrcecho 'export VIRTUALENVWRAPPER_VIRTUALENV=/usr/local/bin/virtualenv' >>~/.bashrcecho 'source /usr/local/bin/virtualenvwrapper.sh' >>~/.bashrcexec "$SHELL"echo $WORKON_HOME
When we execute
echo $WORKON_HOMEif we can get a location to a
.virtualenvsdirectory, it means that our installation was successful.
In order to create a virtual environment, you can use the
mkvirtualenvcommand with a name of your choice for your new virtual environment.
As can be seen above, a new virtual environment is created and activated. If we check the locations of Python and pip we can see that they are pointing to a different location than the system locations. Also, we can validate that we are working on a different environment by checking the installed pip packages.
We can list the available virtual environments with the
Also, we can activate the virtual environment of our choice with the
workoncommand with the name of our virtual environment.
In order to deactivate a virtual environment, you can use the
deactivatecommand. You can check if a virtual environment is activated or not by checking the beginning of your terminal name.