Python virtual environment
How do I create and manage virtual environment to test projects locally
Python is not a very good and well managed and organized language. It can get pretty messy, if you don’t create boundaries. Installing packs, managing multiple versions, messing up with the system python… There are countless problems related to this language.
BUT, It is not the worst tool in the world. It is easy to start and if you follow good practices, it can be really good!
One of the tools that I use to keep my system python clean and run my projects is the virtual environment. With it, i can create a new virtual environment for each project and use it to do whatever I want!
Python - managing multiple versions
I There are multiple options for managing python versions, and the one that I have chosen
to work with is
pyenv.
So, a quick run here on how to isntall a new python version with it:
1 - List all the available versions of python:
pyenv install --list
In this phase, you can use the grep command, to see an specific version of python that you are looking for. This option, for example will list all the versions, 3.6, 3.7 e 3.8 related.
pyenv install --list | grep " 3\.[678]"
2 - Install the version you want
After selecting the version that you want to install, copy the version number and install it. The example below
is displaying how to install version 3.10.2
.
pyenv install -v 3.10.2
3 - Switch to the new python version
- List the available versions with
pyenv versions
. - Select the desired version, from the list of installed versions using
pyenv global 2.7.15
- Check your version with
python3 -V
Now you are ready to create the new virtual environment.
Creating the virtual environments
To create the virtual environments, you will need to install the python virtual environment.
1 - Install it on your current
python version python3 -m pip install virtualenv
.
2 - Create your virtual env python3 -m venv /path/to/new/virtual/environment
.
3 - Now activate it, and use. Remember that yo install packages and tools, always use python3 -m pip
. This way you avoid installing packages on
your virtual environment.