DEV Community

Cover image for Installing Python3 Virtual Environment on Ubuntu 20.04
luthfisauqi17
luthfisauqi17

Posted on • Updated on

Installing Python3 Virtual Environment on Ubuntu 20.04

If you are interested, you can also watch the video version of this article:

Outline:

  1. What is a virtual environment?
  2. How to install a Python3 virtual environment?
  3. How to use the virtual environment?

1. What is a 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.

2. How to install a Python3 virtual environment?

  • 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
Enter fullscreen mode Exit fullscreen mode

The output should be like this:

Python 3.8.10
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode

3. How to use the virtual environment?

  • To use the virtual environment, you can type this in your terminal:
python3 -m venv my-project-env
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.


Sources and Images:

Top comments (0)