Docs / Programming & Development / Setting Up a Python Virtual Environment on Linux

Setting Up a Python Virtual Environment on Linux

By Admin · Feb 25, 2026 · Updated Apr 23, 2026 · 91 views · 1 min read

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
deactivate

Using 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.1

Requirements Files

# Freeze current dependencies
pip freeze > requirements.txt

# Install from requirements
pip install -r requirements.txt

Using 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 environment

Best 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

Was this article helpful?