Venv Tutorial
TL;DR
Virtual environments create isolated Python installations to prevent package conflicts between projects using python -m venv
.
Interesting!
Virtual environments solve the “dependency hell” problem - you can have different versions of the same library for different projects without conflicts!
Creating a Virtual Environment
bash code snippet start
# Create a new virtual environment
python -m venv myproject-env
# Activate it (Unix/MacOS)
source myproject-env/bin/activate
# Activate it (Windows)
myproject-env\Scripts\activate
bash code snippet end
When activated, your prompt shows the environment name: (myproject-env) $
Managing Packages
bash code snippet start
# Install packages
python -m pip install requests
python -m pip install numpy==1.21.0
# List installed packages
python -m pip list
# Save requirements
python -m pip freeze > requirements.txt
# Install from requirements
python -m pip install -r requirements.txt
bash code snippet end
Common Workflow
bash code snippet start
# Create and activate environment
python -m venv .venv
source .venv/bin/activate
# Install project dependencies
pip install -r requirements.txt
# Work on your project...
# Deactivate when done
deactivate
bash code snippet end
Best Practices
- Use
.venv
as your environment directory name (it’s gitignored by default) - Always activate before installing packages
- Use
requirements.txt
to track dependencies - Deactivate when switching projects
Virtual environments keep your projects clean and your global Python installation uncluttered! Use venv with module organization and command-line tools . Essential for database projects and works seamlessly with path management for project structure.
Reference: Virtual Environments and Packages