Generating PDF…

Preparing…
← Back

Python Virtual Environments, Conda & Package Management

Computer Programming 2 — Practical Session 2

Why Virtual Environments & Multi-Python Versions?

In modern software engineering, running every project in your main global Python setup leads to dependency conflicts and broken apps.

  • Global Package Conflicts: Project A requires pandas==1.5, but Project B needs pandas==2.2. Installing globally overwrites the older version.
  • Python Version Mismatches: Legacy code requires Python 3.9, while your new AI library requires Python 3.11+.
  • Clean Reproducibility: Team members and deployment servers need to reproduce the exact environment in one command.
# The Danger of Global Installation ⚠️
$ pip install pandas==1.5.3
Installing pandas 1.5.3... Done.

$ pip install pandas==2.2.0
Uninstalling pandas 1.5.3... 💥 (Project A breaks!)

# The Solution: Isolated Environments 🛡️
(project_a_env) $ pip install pandas==1.5.3
(project_b_env) $ pip install pandas==2.2.0
# Both projects run smoothly on the same computer!

Part 1 — Standard Python venv

Python includes the venv module out of the box. It creates a lightweight directory containing an isolated Python executable and site-packages.

  • Windows Command: python -m venv myenv
  • macOS/Linux Command: python3 -m venv myenv

Inside the myenv/ Folder:

📁 bin/ (macOS/Linux) or Scripts/ (Windows) — Activation scripts & binaries.
📁 lib/python3.x/site-packages/ — Isolated installed libraries.
📄 pyvenv.cfg — Environment config pointing to base Python executable.

# Step 1: Open Terminal / PowerShell in your project directory
$ cd ~/projects/my_app

# Step 2: Create a virtual environment named 'env'
$ python3 -m venv env

# Step 3: Check directory contents
$ ls -l
drwxr-xr-x  env/        <-- Isolated environment folder
-rw-r--r--  main.py     <-- Your project source code

Part 2 — Activating & Deactivating venv

Creating an environment doesn't use it automatically. You must activate it before running pip or executing scripts.

Activation Commands by OS:

  • macOS / Linux: source env/bin/activate
  • Windows PowerShell: .\env\Scripts\Activate.ps1
  • Windows Command Prompt: .\env\Scripts\activate.bat

Visual Check: Look for (env) at the start of your terminal prompt line!

To Exit: Simply type deactivate.

# Activate on macOS/Linux:
$ source env/bin/activate
(env) $ python --version
Python 3.11.4

# Verify pip location points inside 'env':
(env) $ which pip
/Users/reza/projects/my_app/env/bin/pip

# Exit the environment:
(env) $ deactivate
$ 

Part 3 — Custom Python Versions with Conda

Standard venv uses whatever base Python version is installed on your operating system. What if you need Python 3.10 when your system runs 3.12?

Enter Anaconda / Miniconda 🐍
  • Create Conda Env with Specific Python:
    conda create -n py310env python=3.10
  • Activate Conda Env:
    conda activate py310env
  • List All Conda Envs:
    conda env list
  • Deactivate:
    conda deactivate
# 1. Create a Conda env named 'ai_lab' with Python 3.10
$ conda create -n ai_lab python=3.10 -y

# 2. Activate the environment
$ conda activate ai_lab
(ai_lab) $ python --version
Python 3.10.12

# 3. View installed conda environments
$ conda env list
# conda environments:
#
base                     /opt/anaconda3
ai_lab                *  /opt/anaconda3/envs/ai_lab

Interactive Terminal Simulator: venv vs Conda

Click the buttons below to simulate activating and using environments in real time!

bash — ~/dev/project
$ python3 -m venv env
$ Ready to test commands... Click buttons above to switch environment mode!

Part 4 — Package Management (pip & conda install)

Once your environment is active, any package you install is isolated strictly within that environment.

  • Installing Packages via pip:
    pip install requests colorama tabulate
  • Installing Packages via Conda:
    conda install numpy pandas
  • Listing Packages:
    pip list (shows only libraries installed in active environment)
  • Package Info:
    pip show requests
# Activate environment
$ source env/bin/activate

# Install third-party packages
(env) $ pip install requests colorama
Collecting requests...
Successfully installed colorama-0.4.6 requests-2.31.0

# Inspect installed libraries
(env) $ pip list
Package    Version
---------- -------
colorama   0.4.6
pip        23.2.1
requests   2.31.0

Part 5 — Reproducible Environments (requirements.txt)

Never send your env/ folder to teammates. Instead, export a dependency manifest!

📄 Standard pip Manifest:

Export: pip freeze > requirements.txt
Install on New Machine: pip install -r requirements.txt

⚡ Conda Environment File:

Export: conda env export > environment.yml
Install on New Machine: conda env create -f environment.yml

# Content of requirements.txt
colorama==0.4.6
requests==2.31.0
urllib3==2.0.4

# Workflow for a new team member:
$ git clone https://github.com/user/app.git
$ cd app
$ python3 -m venv env
$ source env/bin/activate
(env) $ pip install -r requirements.txt
# Environment perfectly reproduced in 5 seconds! 🚀

Hands-On Challenge 1 — Colorized Weather App

Your Task: Create a mini CLI app inside a fresh virtual environment.

  1. Create directory weather_cli and navigate into it.
  2. Create and activate a virtual environment named env.
  3. Install colorama and requests via pip.
  4. Create app.py and print a colored status message.
  5. Export dependencies to requirements.txt.
# app.py
import requests
from colorama import Fore, Style, init

init(autoreset=True)

print(Fore.CYAN + "=== Weather CLI App ===")
print(Fore.GREEN + "Status: Virtual Environment Active! 🚀")

# Mock request to test requests library
response = requests.get("https://api.github.com")
print(f"API Connectivity Check: Status {response.status_code}")

Hands-On Challenge 2 — The Isolation Test

Goal: Prove that environment isolation works by forcing a failure and rebuilding!

  1. Deactivate your active (env): type deactivate.
  2. Create a second environment: python3 -m venv clean_env.
  3. Activate clean_env and try running python app.py.
  4. Observe the error: ModuleNotFoundError: No module named 'colorama'.
  5. Fix it instantly using pip install -r requirements.txt!
# Experience the real-world developer scenario!
(env) $ deactivate
$ python3 -m venv clean_env
$ source clean_env/bin/activate
(clean_env) $ python app.py
Traceback (most recent call last):
  File "app.py", line 2, in 
    from colorama import Fore
ModuleNotFoundError: No module named 'colorama'

# Rebuild dependencies:
(clean_env) $ pip install -r requirements.txt
(clean_env) $ python app.py
=== Weather CLI App === (Works cleanly!)

Troubleshooting Map & Common Pitfalls

⚠️ PowerShell Script Execution Disabled

Error: cannot be loaded because running scripts is disabled on this system.
Fix (PowerShell as Admin):
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

⚠️ Conda Command Not Found

Error: conda: command not found.
Fix: Run conda init bash or conda init powershell, then restart your terminal window.

⚠️ Installing Packages in Wrong Location

Symptom: Installed package isn't recognized in VS Code.
Fix: Check which pip / where pip. Make sure (env) appears in your terminal before running pip install!

Best Practices & Git Integration (.gitignore)

Virtual environment folders (env/, venv/) contain thousands of OS-dependent binaries. They must NEVER be pushed to GitHub!

The Golden Rule of Environment Version Control:

COMMIT: Source code (*.py), requirements.txt, environment.yml, .gitignore.
NEVER COMMIT: env/, venv/, __pycache__/, .env secrets.

# Standard .gitignore for Python Projects
# Ignore virtual environments
env/
venv/
ENV/
.venv/
anaconda/

# Ignore bytecode & caches
__pycache__/
*.pyc

# Ignore secret environment variables
.env

Interactive Quiz 1 — Fill in the Blank (venv & pip)

Fill in the missing command keywords below and click Check Answer!

Question 1: Creating a Virtual Environment

Fill in the missing module flag to create a virtual environment named myenv:

$ python3 - venv myenv

Question 2: Exporting Requirements

Fill in the missing pip subcommand to write installed packages to requirements.txt:

(env) $ pip > requirements.txt

Interactive Quiz 2 — Fill in the Blank (Conda & Activation)

Test your Conda and environment activation knowledge below!

Question 3: Conda Custom Python Version

Fill in the missing parameter to create a Conda environment named py310 with Python version 3.10:

$ conda create -n py310

Question 4: macOS/Linux Activation Script

Fill in the missing shell command used to execute the activation script on macOS/Linux:

$ env/bin/activate

Command Quick Reference Card

Action Standard Python venv Anaconda / Conda
Create Environment python3 -m venv env conda create -n myenv python=3.10
Activate (macOS/Linux) source env/bin/activate conda activate myenv
Activate (Windows) .\env\Scripts\Activate.ps1 conda activate myenv
Deactivate deactivate conda deactivate
Export Config pip freeze > requirements.txt conda env export > environment.yml

Practical 2 Completed! 🎉

You now possess professional industry skills to isolate environments, manage third-party libraries, handle multi-version Python installs, and write clean requirements.txt files.

✅ Practical Checklist

• Created & activated venv.
• Installed & managed packages with pip.
• Tested Conda custom Python versions.
• Generated requirements.txt.

🔮 Looking Ahead to Week 3

• Object-Oriented Programming (OOP).
• Classes, Objects & Instantiation.
• Instance Attributes & Methods.
• Encapsulation Fundamentals.