Why Virtual Environments?
Virtual environments isolate Python dependencies per project. This prevents version conflicts between projects and keeps your system Python clean.
Using venv (Built-in)
# Create a virtual environment
python3 -m venv myproject-env
# Activate it
source myproject-env/bin/activate
# Your prompt changes to show the active environment
(myproject-env) $ pip install flask requests
# Deactivate when done
deactivateUsing pyenv for Multiple Python Versions
# Install pyenv
curl https://pyenv.run | bash
# Add to ~/.bashrc
export PYENV_ROOT="$HOME/.pyenv"
export PATH="$PYENV_ROOT/bin:$PATH"
eval "$(pyenv init -)"
# Install Python versions
pyenv install 3.12.1
pyenv install 3.11.7
# Set per-project version
cd myproject
pyenv local 3.12.1Requirements Files
# Freeze current dependencies
pip freeze > requirements.txt
# Install from requirements
pip install -r requirements.txtUsing Poetry (Modern Alternative)
curl -sSL https://install.python-poetry.org | python3 -
poetry new myproject
cd myproject
poetry add flask requests
poetry install
poetry shell # activate environmentBest Practices
- Never install packages with
sudo pip install - Always use virtual environments for project dependencies
- Pin dependency versions in production:
flask==3.0.1 - Add
venv/and.venv/to your.gitignore