Virtual Environment (venv) is a tool used to create a virtual environment for running Python projects, separating libraries and packages from each other, allowing each project to have different versions of libraries without affecting the main Python system.
Why use Virtual Environment?
Separate packages for each project – Prevents package conflicts when working on multiple projects
Version control of libraries – Allows you to specify a specific version of a package for that project
Make projects more portable – Share requirements.txt so others can install the same package
Prevent issues with the core Python system – Does not affect packages installed across machines
Using a Virtual Environment
- Create a Virtual Environment
python -m venv venv
This command creates a venv folder that contains all the libraries for that project.
- Activate the Virtual Environment
Windows (cmd)
venv\Scripts\activate
Windows (PowerShell)
venv\Scripts\Activate.ps1
macOS/Linux
source venv/bin/activate
3.Install the libraries in the Virtual Environment
pip install requests
- Save the list of libraries used
pip freeze > requirements.txt
Use this file to share with others or install all the libraries on a new machine:
pip install -r requirements.txt
- Close the Virtual Environment
deactivate
In short, venv allows each project to have its own Python and libraries.
It helps manage packages and prevents compatibility issues.
It is easy to use and is a best practice in Python.