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:
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):
myenv\Scripts\activate
✅ On Windows (PowerShell):
myenv\Scripts\Activate.ps1
✅ On macOS/Linux:
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:
pip install django
🔹 These packages are stored inside myenv/
, not globally.
4️⃣ Deactivate the Virtual Environment
To exit the virtual environment, run:
deactivate
🔹 This returns you to the system-wide Python environment.
5️⃣ Delete a Virtual Environment (If Needed)
Simply remove the folder:
rm -rf myenv # macOS/Linuxrmdir /s /q myenv # Windows
3. Bonus: Using virtualenv
(Alternative to venv
)
If venv
is missing, install virtualenv:
pip install virtualenv
Then, create an environment:
virtualenv myenv
4. Checking Installed Packages in a Virtual Environment
pip list
Or save the list for deployment:
pip freeze > requirements.txt
To install from this file in another environment:
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