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?
Section titled “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?
Section titled “2. Use of Python Virtual Environment?”1️⃣ Create a Virtual Environment
Section titled “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
Section titled “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
Section titled “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
Section titled “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)
Section titled “5️⃣ Delete a Virtual Environment (If Needed)”Simply remove the folder:
rm -rf myenv # macOS/Linuxrmdir /s /q myenv # Windows3. Bonus: Using virtualenv (Alternative to venv)
Section titled “3. Bonus: Using virtualenv (Alternative to venv)”If venv is missing, install virtualenv:
pip install virtualenvThen, create an environment:
virtualenv myenv4. Checking Installed Packages in a Virtual Environment
Section titled “4. Checking Installed Packages in a Virtual Environment”pip listOr save the list for deployment:
pip freeze > requirements.txtTo install from this file in another environment:
pip install -r requirements.txt5. Summary
Section titled “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