Search notes:

Python standard library: venv

The venv module can be used to create virtual Python environments. In each environment, a set of packages can be installed independently from another environment, thus reducing the change of breaking functioniality when upgrading packages etc.
Such a virtual environment exists in a directory.
With Python 3.3, venv has become the preferred way to create and manage virtual environments.

Creating a virtual environment

A virtual environment (in the directory /path/to/the/env/dir) is created like so:
$ python -m venv /path/to/the/env/dir

Activating a virtual environment

Within the created directory tree is a script that can be called from the command line to activate a virtual environment. This script is located in the subdirectory /path/to/the/env/dir/Scripts (Windows) or /path/to/the/env/dir/bin (Linux) and comes in multiple versions (PowerShell script, cmd.exe batch file, c-shell etc.)
This script is named activate and has the filename suffix corresponding to the version.
After activating a virtual environment, the most important effect seems to be that /path/to/the/env/dir and /path/to/the/env/dir/lib/site-packages are added to sys.path.
$ /path/to/the/env/dir/bin/activate
(env) $ which python
/path/to/the/env/dir/bin/python
…
(env) $ echo $VIRTUAL_ENV
/path/to/the/env/dir/bin
…
(env) $ python
>>> import sys
>>> print (sys.prefix)
/path/to/the/env/dir

Deactivating a virtual environment

When a virtual environment is activated, a global function named deactivate is made available to the shell.
Calling this function deactivates the environment:
(env) $ deactivate
$ …

Verifying if a virtual environment is active

When a virtual environment is activated, the environment variable VIRTUAL_ENV is set.
The value of this environment variable points to the directory with the virtual environment.

ModuleNotFoundError: No module named '…'

A Python script with a shebang (/usr/bin/python3) that imports a module which was installed into a virtual directory is likely to throw the ModuleNotFoundError: No module named '…' error because /usr/bin/python3 looks for the modules in the system's module directories rather than in the virtual environment's module directory.
$ ./the-script.py
ModuleNotFoundError: No module named '…'

$ python3 ./the-script.py
…

Removing an environment

If a virtual environment is not used anymore, it can be removed by deleting the directory:
rm -rf /path/to/the/env/dir

Debian/Ubuntu

$ python3 -m venv ~/py-venv

The virtual environment was not created successfully because ensurepip is not
available.  On Debian/Ubuntu systems, you need to install the python3-venv
package using the following command.

    apt-get install python3-venv

You may need to use sudo with that command.  After installing the python3-venv
package, recreate your virtual environment.

Links

Compare with virtualenv.
Pipenv is a Python virtual environment management tool.

Index