Lesson 19: Virtual Environments in Python

๐ŸŽฏ Lesson Objective

To understand how to create and manage isolated Python environments using virtual environments, keeping project dependencies organized and avoiding conflicts.


๐Ÿงฉ 1. What Is a Virtual Environment?

A virtual environment is an isolated workspace that allows you to:

  • Install project-specific Python packages
  • Avoid conflicts with other projects
  • Work on multiple Python versions simultaneously

It keeps dependencies separate from the system Python.


โš™๏ธ 2. Creating a Virtual Environment

โœ… Using venv (built-in module)

# Create a virtual environment named 'myenv'
python -m venv myenv
  • This creates a folder myenv/ with isolated Python binaries and libraries.

๐Ÿ”„ 3. Activating the Virtual Environment

OSCommand
Windowsmyenv\Scripts\activate
macOS/Linuxsource myenv/bin/activate

โœ… Example:

# Activate on Windows
myenv\Scripts\activate

# Activate on Linux/macOS
source myenv/bin/activate

After activation, your command prompt shows (myenv) indicating the environment is active.


๐Ÿงฐ 4. Installing Packages in a Virtual Environment

pip install requests
pip install numpy
  • Packages installed here do not affect system Python.
  • Check installed packages:
pip list

๐Ÿงฑ 5. Deactivating the Virtual Environment

deactivate
  • Returns to system Python.

๐Ÿ”„ 6. Removing a Virtual Environment

  • Simply delete the environment folder:
rm -rf myenv   # macOS/Linux
rmdir /s myenv # Windows

๐Ÿ› ๏ธ 7. Requirements File

  • Save installed packages for project sharing:
pip freeze > requirements.txt
  • Install packages from requirements:
pip install -r requirements.txt

๐ŸŒ 8. Real-Life Example โ€“ Project Setup

  1. Create virtual environment for web_scraper_project
python -m venv web_scraper_env
  1. Activate environment
source web_scraper_env/bin/activate
  1. Install dependencies
pip install requests beautifulsoup4
  1. Run your scraper script
python scraper.py
  1. Deactivate environment after work
deactivate

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *