There are several ways to create a Python virtual environment, depending on the Python version you are running.
Before you read on, I want you to point you to another tool, called pipenv. It combines the functionality of tools that you are about to learn; virtualenv and pip. Futher on in this chapter, I will describe pipenv in detail.
If you are running Python 3.4+, you can use the venv module baked into Python:
$ python -m venv [directory]
This command will create a venv in the specified directory and copy pip and easy_install into it too.
The alternative that works for any Python version is using the virtualenv package. You may need to install it first, system-wide, with:
$ sudo pip install virtualenv
Once installed, you can create a virtual environment with:
$ virtualenv [directory]
We activate our virtual environment with the source command. If you created your venv in the myvenv directory, the command would be:
$ source myvenv/bin/activate
That’s it! We’re ready to rock!
When you activate a virtual environment, your
$PATH variable is changed. You can see it for yourself, by printing the path with
echo $PATH. In my case, it looks like this:
As you can see, the bin directory of your venv is put in front of everything else, overriding all the system-wide Python software.
If you take a look inside the directory of your venv (in this case:
myvenv), you’ll see something like this:
You can see that:
If you are done working on your project, it’s a good habit to deactivate its venv. Without deactivating it, all other Python code you execute will also run inside of it.
Deactivating your virtual environment couldn’t be simpler. Just enter this:
If you liked this page, please share it with a fellow learner: