Skip to content

venv

When developing Python applications, the system typically has only one version of Python 3 (3.x). All third-party packages installed via pip go into the Python 3 site-packages directory.

The Need for Isolation

If you're developing multiple applications, they will share the same Python environment. For example, if Application A needs Jinja 2.7 and Application B requires Jinja 2.6, conflicts arise.

To solve this, each application can have its own "isolated" Python runtime environment using venv.

Creating a Virtual Environment

Let’s assume you're starting a new project named project101 and need a dedicated Python environment:

  1. Create a Directory: First, create a directory for your virtual environment. Here, we'll name it proj101env:

    bash
    $ mkdir proj101env
    $ cd proj101env/
  2. Set Up the Virtual Environment: Create an isolated Python environment:

    bash
    proj101env$ python3 -m venv .

    After running this command, you will see several folders and a pyvenv.cfg file:

    bash
    proj101env$ ls
    bin  include  lib  pyvenv.cfg

    The command python3 -m venv <directory> sets up an independent Python environment. The bin directory contains executable files like python3 and pip3, which are symlinks to the system Python installation.

  3. Activate the Virtual Environment: Change into the bin directory and activate the environment. On Linux/Mac, use:

    bash
    proj101env$ cd bin
    bin$ source activate

    On Windows, use:

    bash
    proj101env$ activate.bat

    Your command prompt will change to indicate that the proj101env environment is active:

    bash
    (proj101env) bin$
  4. Install Packages: Now you can install packages without affecting the system Python environment:

    bash
    (proj101env) bin$ pip3 install jinja2

    You can verify the installation:

    bash
    (proj101env) bin$ python3
    >>> import jinja2
    >>> exit()

    Packages installed in the venv environment go into proj101env/lib/python3.x/site-packages, keeping the system environment untouched.

  5. Deactivate the Environment: To exit the virtual environment, simply run:

    bash
    (proj101env) bin$ deactivate

    You'll return to the normal system environment, where pip and python point to the system installation.

Deleting a Virtual Environment

If you no longer need a particular venv, such as proj101env, you can easily delete it. Ensure it's not activated, then remove the directory:

bash
$ rm -rf proj101env

Summary

venv provides isolated Python environments for applications, helping to avoid conflicts between different versions of packages required by various applications. This isolation allows for better management of dependencies across projects.

venv has loaded