How to create virtual environments in ubuntu

Why create a virtual environment?

  • Creating virtual environments in Python is important because it provides isolation, reproducibility, portability, flexibility, and maintainability to your projects. 
  • It allows you to create isolated environments with their own set of dependencies, ensuring that each project has its own sandboxed environment. 
  • Virtual environments also make it easier to reproduce the same environment with the same package versions in the future, share and distribute projects with their dependencies in a self-contained manner, manage dependencies at a granular level, and maintain projects over the long term. 
  • Using virtual environments is a best practice that helps ensure robust and reliable Python software development.

Create virtual environment

I'm using Ubuntu 22.4 here, first of all, I'm going to verify the Python version on my machine.
 python3 --version
Output :

Now start the setup of the virtual environment to set up we need venv module. So let's start the package python3-venv to get venv module.
 sudo apt install python3-venv
Output : 
Once the module gets installed we are ready to create the virtual environment. Now navigate to your directory where you want to create a virtual environment.
 python3 -m venv name-of-venv
The above command will create a virtual environment in your current directory with the name name-of-venv.
To start using the virtual environment we have to activate it.
source name-of-venv/din/activate



Once started the virtual environment it will show in your terminal given in the above image. Now you can install Django, flask, or any other python related task in this environment.
To deactivate the virtual environment you just have to give the command -  
deactivate

Comments