rsapkf

Managing Python Virtual Environments with venv Module

August 07, 2019 | 2 min read | #python, #programming

Note: This article assumes you have python3.3+ and *NIX system installed. Some commands might not work on Windows out of the box (e.g. tree).

If you are a Python developer (beginner or advanced), you are bound to come across having to manage your dependencies in projects in an efficient manner in order to prevent version conflicts between different packages. And you might already know about some tools built in order to do exactly that. Over the years, I've used a number of those tools to manage my projects- virtualenv, virtualenvwrapper, pipenv, pyvenv, etc. But a few months ago, I discovered 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 than all of them, IMO.

The tool I'm talking about is the 'venv' module included in the stdlib of Python3.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 -L 2
myproject/
	myproject/
		...
	venv/
		bin/
		include/
		lib/
		pyvenv.cfg

To activate the virtual environment, just do:

$ source ./venv/bin/activate

Note how 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 global environment and other virtualenvs 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) $

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.


A quick aside: 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

Learn More:

Official Python documentation on venv module.
Stack Overflow discussion on the topic.
Why you should use python -m pip.

Last Updated: September 16, 2019
← Previous
The Rabbithole Series, Part 1
Next →
Enabling Vim Mode In All Major Graphical Text Editors

Got suggestions or feedback ? Contact me!