A Virtual Environment in Python is an isolated environment that allows you to install and manage packages separately for each project. This prevents conflicts between different projects that may require different versions of the same package.
For example, one project may need Django 3.0, while another requires Django 4.0. Virtual environments allow both projects to work without conflicts.
π― Why Use Virtual Environments?
Benefits:
β Avoid package conflicts between projects
β Keep project dependencies organized
β Easily share project requirements
β Maintain a clean global Python installation
π§° Creating a Virtual Environment
Python provides a built-in module called venv to create virtual environments.
Create a Virtual Environment
Open your terminal or command prompt and run:
python -m venv myenv
Here, myenv is the name of the virtual environment folder.
Example:
python -m venv project_env
This creates a folder containing a separate Python environment.
βΆοΈ Activating the Virtual Environment
Before using the environment, you must activate it.
On Windows
myenv\Scripts\activate
On macOS / Linux
source myenv/bin/activate
After activation, the terminal usually shows the environment name:
(myenv) C:\Users\venka\project>
π¦ Installing Packages in the Virtual Environment
Once activated, any package installed with pip will only affect the virtual environment.
Example:
pip install requests
This installs the package only inside the virtual environment, not globally.
π Viewing Installed Packages
You can list installed packages using:
pip list
π Saving Project Dependencies
To save all installed packages into a file:
pip freeze > requirements.txt
Example output:
requests==2.31.0
numpy==1.26.4
This file helps recreate the same environment on another machine.
π₯ Installing Dependencies from requirements.txt
To install packages listed in a requirements file:
pip install -r requirements.txt
βΉ Deactivating the Virtual Environment
To exit the virtual environment, run:
deactivate
This returns you to the system’s global Python environment.
π Example Project Structure
project_folder/
β
βββ myenv/ # Virtual environment
βββ main.py
βββ requirements.txt
π§ Summary
| Command | Purpose |
|---|---|
python -m venv myenv | Create virtual environment |
myenv\Scripts\activate | Activate environment (Windows) |
source myenv/bin/activate | Activate environment (Linux/Mac) |
pip install package | Install package |
pip freeze > requirements.txt | Save dependencies |
deactivate | Exit virtual environment |
β
In simple terms:
A virtual environment allows each Python project to have its own separate packages and dependencies, preventing conflicts between projects.