๐ฏ 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
| OS | Command |
|---|---|
| Windows | myenv\Scripts\activate |
| macOS/Linux | source 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
- Create virtual environment for
web_scraper_project
python -m venv web_scraper_env
- Activate environment
source web_scraper_env/bin/activate
- Install dependencies
pip install requests beautifulsoup4
- Run your scraper script
python scraper.py
- Deactivate environment after work
deactivate

Leave a Reply