19
Installing Python3 Virtual Environment on Ubuntu 20.04
If you are interested, you can also watch the video version of this article:
Outline:
- What is a virtual environment?
- How to install a Python3 virtual environment?
- How to use the virtual environment?
According to an explanation by linuxize.com, Python virtual environment is a self-contained directory tree that includes a Python installation and number of additional packages. The main purpose of Python virtual environments is to create an isolated environment for different Python projects. This way you can install a specific version of a module on a per project basis without worrying that it will affect your other Python projects.
- Before installing the virtual environment, we need to make sure that Python3 is already installed on the machine. On ubuntu, you can open the terminal and type:
python3 -V
The output should be like this:
Python 3.8.10
- In Python itself, there are several ways to install the virtual environment. Currently, the recomended way to install the virtual environment is by using
venv
module.
You can install that module by type this command on the terminal:
sudo apt install python3-venv
- To use the virtual environment, you can type this in your terminal:
python3 -m venv my-project-env
The above command will create a directory called my-project-env
which contains a copy of the python supporting files for the virtual environment.
- In order to use the virtual environment, you have to activate it first. In order to activate it, you can type the following on your terminal:
source my-project-env/bin/activate
After that, you might notice that there is something unique in your terminal. And if it do so, then your virtual environment is ready to go.
To test it, you can type the following command in the terminal:
pip install numpy
The above command will install python numpy package and the above package can only used if you activate the virtual environment.
There you go, that was a simple explanation about a virtual environment in python. Thank you for reading this article, inputs and comments are very appreciated.
19