Virtualenv is the tool for creating a Python virtual environment, a folder on your computer system that
embarks its own copy of the Python interpreter and the site-packages
subfolder where the code for the installed third-party modules is placed.
Using a so-called "virtual env" is recommended so when you work on a given project, your space of dependencies is isolated from the one of another project you might be working on earlier or later that day. Developers create and keep several virtual envs depending on the projects they are working on or the code they maintain.
Let's first see how you use it standalone, and then as a plugin for the pyenv tool.
Using the virtualenv, the default way
In recent versions of Python 3, the "Virtualenv" module is part of the standard library and is called venv
. So you can create and start working with a new virtual env by doing:
$ python3 -m venv mytesting_env
$ cd mytesting_env
$ source bin/activate
(mytesting_env)$
If you have an old version of Python, without the add-on module installed, you can install it using pip, and then use the provided CLI program to create the virtual env:
$ virtualenv mytesting_env
...
Using virtualenv integrated in pyenv
If you choose to use pyenv to manage your Python installations, you can use the virtualenv
tool integrated in it.
This is possible by installing the pyenv-virtualenv plugin on top of pyenv.
In my previous post, I presented how to install pyenv the easier way, using the installer provided by the developer. In fact, when proceding that way, the "pyenv-virtualenv" plugin is already installed for us by default.
To double-check that it is the case, you can go in the $HOME/.pyenv/plugins/
directory, or the equivalent on your computer, and you should find it.
There is a final action needed from your part, though, to make sure things work correctly: Add the pyenv virtualenv-init
command to your shell by putting it at the end of your .bashrc
file.
You can do:
$ echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc
Then restart your shell, for example with:
$ exec "$SHELL"
Now, let's say we want a virtual env based on our Python 3.6.1, where we are going to do stuff using the "requests" module. We can do:
$ pyenv virtualenv 3.6.1 py361_requests_env
...
Then, you only need the following command, anytime you want to use that virtual environment:
$ pyenv activate py361_requests_env
...
(py361_requests_env) $