How to Install Virtualenv on Ubuntu 22.04?

A virtual environment in Python is the most important tool developers use, and this tool keeps the dependencies that are required by other projects isolated in the virtual environment. A Virtualenv can be installed on different distributions of Linux.

This post will explore the possible method to install Virtualenv on Ubuntu. The post’s content is as follows:

Let’s start with the installation first.

How to Install Virtualenv on Ubuntu 22.04?

A few steps are involved in the installation of Virtualenv on Ubuntu, which is explained in the next sections.

Step 1: Install Python3

First of all, if there is no package of Python installed on Ubuntu, then install the Python3 package and for it, add the repository of Python3 using the command:

$ sudo add-apt-repository ppa:deadsnakes/ppa

Then install the Python3 package:

$ sudo apt install python3.9 -y

To confirm the installation of Python, display its installed version:

$ python3.9 --version

The 3.9.13 version of Python has been installed.

Step 2: Install Pip

The next step is to install Pip on Ubuntu, which will help install and create the python scripts. To install Pip, use the package available in the Ubuntu repository with the command:

$ sudo apt install pip -y

Display the installed version of Pip:

$ pip --version

Step 3: Install Virtualenv

Finally, use the pip utility to install the virtual environment on Ubuntu by running the command:

$ sudo apt install python3-venv -y

How to Use Virtualenv on Ubuntu 22.04?

When the virtual environment is installed, make a directory of “MyVirtualEnv” and navigate to it using the command:

$ sudo mkdir MyVirtualEnv && cd MyVirtualEnv

Create a Python-based application with the name of “myapplication”:

$ sudo python3 -m venv myapplication

List down the contents of the application:

$ ls myapplication

Now, activate the environment with the name “myapplication” and use the command:

$ source myapplication/bin/activate

Create a simple program, and for this, create the “myProgram”  file in the “myapplication” environment with the help of a nano text editor:

$ sudo nano myProgram.py

Copy and paste the Python script to display the message of “Welcome to ItsLinuxFoss”:

print(“Welcome to ItsLinuxFoss!”)

Exit the editor by saving the file and run the Python script using the command:

$ python myProgram.py

The message has been displayed on the screen, and now deactivate the virtual environment of Python using the command:

$ deactivate

The Virtual Environment of Python has been closed.

That’s how you can install and use virtualenv on Ubuntu 22.04.

Conclusion

To install Virtualenv on Ubuntu, first, ensure that both python and pip are installed on Ubuntu, then run the command “sudo apt install python3-venv -y” in a terminal. This post has briefly explained the installation of virtualenv on Ubuntu 22.04.