Skip to main content

Managing Python virtual environments with venv module

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

Python is notorious for having a lot of different dependency management tools: virtualenv, virtualenvwrapper, pipenv, pyvenv, pipx, poetry, etc. But the venv module is a fairly new and easier to use tool that comes built-in with Python3.3+. 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 showing the name of the virtualenv. This means that the Python interpreter and libraries installed into it are isolated from those installed in other virtual environments, and 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