This article teaches how to set up a python virtual environment on a Ubuntu 20.04.
An Environment Virtual allows you to manage separate package installations for different projects. They essentially allow you to create a “virtual” isolated Python installation and install packages into that virtual installation.
To create a virtual environment, go to your project’s directory and run venv.
1.- Install python3-venv
sudo apt install python3-venv
2.- Create a Virtual environment
Let’s start by making a project directory and changing into it
mkdir MyScripts cd MyScripts/
Create a virtual environment
python3 -m venv Myvenv
- -m is used to call a module.
- In this example, the virtual environment is called Myvenv
- Usually, the name of the virtual environment is venv, as well as the module
The command before will create a new directory “Myvenv” in our project. This directory is where the Python binary and packages for the virtual environment are.
3.- Activation of the virtual environment:
Activating a virtual environment will put the virtual environment-specific Python and pip executables into your shell’s PATH.
You can confirm you’re in the virtual environment by checking the location of your Python interpreter:
Now that you’re in your virtual environment, you can install packages. For example:
pip install jsons
5.- Deactivate the virtual environment
When you finish your work in your virtual environment, you can deactivate it by running the following command:
Ready! We have learned how to install our virtual environment with Python.
If you are using Python 3.3 or later, the venv module is the preferred way to create and manage virtual environments. If you use Python 2, you should use virtualenv instead of venv.