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

Bash prompt, venv and ArchLabs

If you want to change the command prompt displayed by bash in such a way as to display information about the currently used virtual environment created by venv, you need to modify the PS1 variable in the .bashrc file.

In the ArchLabs distribution, the PS1 variable settings are also modified in the hidden .bash directory in the user’s directory and therefore instead of directly modifying the PS1 variable, the PROMPT_USERFMT variable should be modified, i.e.

PROMPT_USERFMT='\nvenv:(${VIRTUAL_ENV##*/})\n\u@\h:'

Then, the created variable should be exported in the .bashrc file, i.e.

export $PROMPT_USERFMT

To reload bash settings, you need to reload the .bashrc file, i.e.

source .bashrc