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

CommandPurpose
python -m venv myenvCreate virtual environment
myenv\Scripts\activateActivate environment (Windows)
source myenv/bin/activateActivate environment (Linux/Mac)
pip install packageInstall package
pip freeze > requirements.txtSave dependencies
deactivateExit virtual environment

βœ… In simple terms:
A virtual environment allows each Python project to have its own separate packages and dependencies, preventing conflicts between projects.