Skip to main content

Managing Python virtual environments with venv module

7 Aug 2019 · Last updated: 16 Sep 2019 ·
Posted in weblog#tech
Categories: python

Python is notorious for having a lot of different dependency management systems and tools - virtualenv, virtualenvwrapper, pipenv, pyvenv, pipx, poetry, etc. But there is a fairly new tool that comes built-in with Python3 itself that can do almost everything that aforementioned tools can do and is much more elegant and easier to use.

The tool I'm talking about is the venv module included in the stdlib of Python 3.3+. You don't have to install anything on your machine to use it. Just navigate to your project folder and do:

$ python3 -m venv ./venv

Here, the second 'venv' is the name of the virtual environment we want to create.

Now, the project structure looks like:

$ tree myproject -L 2
myproject
├── myproject
│   └── ...
└── venv
    ├── bin
    ├── include
    ├── lib
    └── pyvenv.cfg

To activate the virtual environment, just do:

$ source ./venv/bin/activate

Activating a virtualenv modifies your shell prompt with a little note showing the name of the virtualenv. This means that the Python interpreter, libraries and scripts installed into it are isolated from those installed in other virtual environments, and (by default) in the system Python, leaving the global environment unaffected:

(venv) $ python3 -m pip install django
(venv) $ python3 -m pip list
Django (2.2.6)
pip (9.0.1)
pytz (2019.3)
setuptools (39.0.1)
sqlparse (0.3.0)
...
(venv) $

Before activating a virtual environment, the python command maps to the system version of python interpreter:

$ which python3
/usr/bin/python3

But with an active virtual environment, the python command maps to the interpreter binary inside the active virtualenv:

$ (venv) which python3
/home/$USERNAME/myproject/venv/bin/python3

To deactivate the virtual environment:

(venv) $ deactivate

To export your dependencies to an external file:

(venv) $ python3 -m pip freeze > requirements.txt

Deleting the virtual environment is as simple as deleting the 'venv' directory:

$ rm -rf ./venv

Make sure to deactivate the virtualenv before deleting it.

Further reading