Venv – how to use

The venv library present as a built-in module starting with python 3.3 allows you to create virtual environments.

The virtual environment allows the use of specific versions of libraries, regardless of those that are installed in the default system locations. This prevents errors when the new, updated version of the library does not work well with the rest of the project (the project requires an earlier version).

To create a virtual environment for the current project, type:

python -m venv project_name/env_name

A env_name directory is created in the project directory project_name that contains a virtual environment.

The virtual environment directory contains several subdirectories, including / bin directory containing a link to the python interpreter, as well as an activate file to start the environment. In addition, the env_name directory also has a /lib directory containing installed modules (site-packages).

To run the created environment named env_name, enter in the shell:

source project_name/env_name/bin/activate

You can close the environment with the deactivate command.

When we have a virtual environment running, the newly installed libraries are available only in the selected virtual environment. You can save the library required for the project in a text file with:

pip freeze > requirements.txt

If you have a requirements.txt file describing the project requirements for libraries and their versions, you can install them with:

pip install -r requirements.txt

Leave a Reply

Your email address will not be published. Required fields are marked *