In a previous article, I talked about creating isolated Python environments with Virtualenv. Even though you can spin up isolated environments simply, we can optimize the process to create such environments even more with a Python manager Pyenv Plugin called Pyenv-virtualenv.
This tutorial is done using a Mac. The link to the previous Virtualenv article can be found here: https://www.publish0x.com/dev-things/virtualenv-isolated-environments-for-python-programming-xqqmr
What is Pyenv-Virtualenv?
Pyenv-Virtualenv takes Virtualenv to the next step. With Pyenv-Virtualenv, you can install any Python version and spin up a new Virtualenv without creating the folder in the project yourself. You can activate the environment in any directory.
Installing Pyenv-Virtualenv
Let’s install Pyenv-Virtualenv. Since I am on a Mac, we can just use brew. If you don’t have brew installed you can install it with this command:
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
After installing brew, we can simply install everything using this command:
$ brew install pyenv-virtualenv
$ echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bash_profile
$ source ~/.bash_profile
Then you can validate your install using this command:
Using Pyenv-Virtualenv for Virtualenv Control
Now that you have Pyenv installed, we can start installing multiple versions of Python. Let’s first install Python 2.7 and 3.6 using these commands:
# Choose one of them
$ pyenv install 2.7.1
$ pyenv install 3.6.1
Then let’s check if they installed correctly:
Now let’s create a Virtualenv with Pyenv
# Choose the version you installed earlier
$ pyenv virtualenv 2.7.1 python2env
$ pyenv virtualenv 3.6.1 python3env
Now that we have created a virtualenv using Pyenv we can see all the virtualenv’s that are created.
You should see the name of the virtualenv you created show up with that Python version with this command:
$ pyenv virtualenvs
Now we can activate our virtualenv’s with pyenv with this command:
# Choose the one you install earlier
$ pyenv activate python2env
$ pyenv activate python3env
Then we can easily deactivate them with this command:
Conclusion
That’s really all you need to know. You can still pip freeze your requirements.txt
Resources used to make this article
- Link to Pyenv: https://github.com/pyenv/pyenv#homebrew-on-macos
- Link to Pyenv-Virtualenv: https://github.com/pyenv/pyenv-virtualenv
- Link to Virtualenv: https://virtualenv.pypa.io/en/latest/
- Link to Photo Used in the Article with free license to use: https://www.pexels.com/photo/blur-close-up-code-computer-546819/
- Link to original Medium Article Written by me: https://medium.com/@devthings/pyenv-virtualenv-a-virtual-environment-manager-pyenv-plugin-d321cb4f3227