Create python virtual environment

Written by
Date: 2020-05-20 20:05:00 00:00

To work with Python projects, it is advisable to create virtual environment, that way each project can have its own modules, and even differente versions of modules and does not interfere with another one.

We are going to use python3 and Ubuntu 20.04 for this tutorial.

Install python venv

sudo apt install python3-venv

Create your virtual environment

Virtual environments are based on directory tree, so you first need to go to the directory where you want the virtual environment to be, and then run:

python3 -m venv env

This will create a directory env and will put inside it all pip, modules, and python itself. If you are working on a git repository, be sure to add then env folder to the .gitignore file.

Activate your virtual environment

Now that we have created the virtual environment, we need to activate it:

source env/bin/activate

Your prompt may change from this:

ggarron@DESKTOP-A32PERG:~/my-sites/my-py-app$

To this:

(env) ggarron@DESKTOP-A32PERG:~/my-sites/my-py-app$

This is the moment, when you can install the python modules you need for your project.

Deactivate the virtual environment

Once you finish working on the project, you can deactivate the virtual invoronment.

deactivate

Final words

It is really usefull to work on virtual environments, when you develop with python, you can now work knowing you are not going to mess your system by installing software with pip and not with the operating system own package manager.