How to create a python virtual environment on Ubuntu 22.04.

Vishal RathoreVishal Rathore
2 min read

Most of the time when we are working on python projects, we have to install different dependencies that help us achieve different project goals. It is important that we create virtual environments for each and every python project so as to keep the specific project dependencies isolated from the rest of other project and from ower main ubnutu system.

1. System update.

First and foremost, to ensure that your system is up to date, run the command below

sudo apt update

Next, run the following apt command

sudo apt upgrade

2. Pip install.

After making sure your system is up to date with the latest packages using the above commands, we will then install pip. We will install pip by running the command below

sudo apt install python3-pip

3. Virtualenv install.

Virtualenv is used to isolate virtual environments for python projects.We install it using pip3 by running the command below.

sudo pip3 install virtualenv

4. Creating a virtual environment.

To use venv (virtual environments) in your project, you have to create a new project folder, cd to the project folder in your terminal, and run the following command:

virtualenv .venv

Point to note: You can use your any preferred name in place of “.venv”.

5. Activating virtual environment.

Now that you have created the virtual environment, you will need to activate it before you can use it in your project. On a mac or Linux, to activate your virtual environment, run the code below:

This below command will work only for MacOS and Linux Distros.

source .venv/bin/activate

Nice! Our python virtual environment is now set up and activated. Now you can install any dependencies in your main project and continue you work.

6. Deactivating the virtual environment.

For one reason or the other, we might need to deactivate our environment. To do this, we run the command below.

deactivate

Now you have a step by step guide on how to create, activate, and deactivate a python environment.

Good luck !

0
Subscribe to my newsletter

Read articles from Vishal Rathore directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vishal Rathore
Vishal Rathore

Self-Taught Software Engineer | Technical Writing | Blogging on @Hashnode | Open Source Contributor | Write around career, development and Self Experience.