Skip to content

3. Python Virtual Env

A Python Virtual Environment (venv) 🚀 is an isolated workspace for Python projects. It allows you to install packages without affecting the system-wide Python installation or other projects.

1. Why Use a Virtual Environment?

Project Isolation: Each project can have its own dependencies (Django, Flask, NumPy, etc.).
Avoid Conflicts: Prevent package version conflicts between different projects.
Easier Deployment: Ensures your project runs with the correct dependencies in production.
No Admin Rights Needed: Install packages without modifying global Python.

2. Use of Python Virtual Environment?

1️⃣ Create a Virtual Environment

Run the following command in your project directory:

Terminal window
python -m venv myenv

🔹 This creates a folder called myenv/, which contains a local Python installation and pip.

2️⃣ Activate the Virtual Environment

You need to activate it before installing packages.

On Windows (Command Prompt):

Terminal window
myenv\Scripts\activate

On Windows (PowerShell):

Terminal window
myenv\Scripts\Activate.ps1

On macOS/Linux:

Terminal window
source myenv/bin/activate

🔹 After activation, you’ll see myenv in the terminal prompt, indicating the environment is active.

3️⃣ Install Packages in the Virtual Environment

Once activated, install packages like Django:

Terminal window
pip install django

🔹 These packages are stored inside myenv/, not globally.

4️⃣ Deactivate the Virtual Environment

To exit the virtual environment, run:

Terminal window
deactivate

🔹 This returns you to the system-wide Python environment.

5️⃣ Delete a Virtual Environment (If Needed)

Simply remove the folder:

Terminal window
rm -rf myenv # macOS/Linux
rmdir /s /q myenv # Windows

3. Bonus: Using virtualenv (Alternative to venv)

If venv is missing, install virtualenv:

Terminal window
pip install virtualenv

Then, create an environment:

Terminal window
virtualenv myenv

4. Checking Installed Packages in a Virtual Environment

Terminal window
pip list

Or save the list for deployment:

Terminal window
pip freeze > requirements.txt

To install from this file in another environment:

Terminal window
pip install -r requirements.txt

5. Summary

1️⃣ python -m venv myenv → Create virtual environment
2️⃣ source myenv/bin/activate (Linux/macOS) / myenv\Scripts\activate (Windows) → Activate it
3️⃣ pip install <package> → Install dependencies
4️⃣ deactivate → Exit the virtual environment