Categories
Automated testing Python

Python virtual environment with venv

Venv is a python package that allows you to use separate virtual environments for every python project you have. Once activated, it modifies the PATH environment variable with a custom bin directory that is located inside you virtual environment.

Why do you need a virtual environment

If you work with more than one python project on your computer you can get in trouble with modules’ versions. I case if these applications need same module but different versions of it you will be able to use only one of them.

Additionally, a virtual environment gives you a possibility to control what dependencies has you application. And then you can easily specify these dependencies in the requirements.

One more advantage – inside an activated virtual environment you can run python modules in an easier way. For example:

pytest

instead of

python -m pytest

Install venv

Generally, venv is a part of the Python3 and you don’t need to install anything. But if you use Ubuntu/Debian you need to install venv by yourself. You can do it with the following command

sudo apt-get install python3-venv

Create a virtual environment with venv

To create a virtual environment go to the root directory of your project and run

python -m venv <dir>

Set any name instead of <dir>. Usually the name is “venv” or “.venv”.

Activate virtual environment

To activate a virtual environment created with venv just go to the project’s root and run

source <dir>/bin/activate

So, if you gave to your virtual environment directory the name “venv”, the command for you will be

source venv/bin/activate

You will see that your terminal’s prompt is changed and now begins with “(source)”.

Deactivate virtual environment

In order to deactivate the virtual environment, run

deactivate

Install python modules into virtual environment

If you want to install any python module into the virtual environment with pip, you need to activate the environment and then run “pip install” as usual

source venv/bin/activate
pip install requests

List modules installed in the virtual environment

To see the list of modules installed in the virtual environment you need to run this command inside the activated virtual environment

pip freeze

In order to save this list to the file “requirements.txt”, run

pip freeze > requirements.txt

By Eugene Okulik