2 min read

Setting up a Python Development Environment

This guide details the modern, professional way to set up a Python development environment on Linux. We will use pyenv to manage different Python versions and venv to create isolated project environments. This prevents the classic "dependency hell" where one project's needs conflict with another's.

1. Prerequisites

Compiling Python from source requires a standard set of build tools.

  • Reference: Post-Install Linux Configuration
  • Action: Ensure build-essential, curl, and other dependencies for pyenv are installed.
    sudo apt install -y build-essential libssl-dev zlib1g-dev libbz2-dev \
    libreadline-dev libsqlite3-dev curl libncursesw5-dev xz-utils \
    tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev

2. Install pyenv (Python Version Manager)

pyenv lets you install and switch between multiple Python versions on the same machine.

  1. Run the installer:
    curl https://pyenv.run | bash
  2. Add to your shell: The script will output instructions to add pyenv to your ~/.bashrc file. It will look similar to this:
    echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
    echo 'command -v pyenv >/dev/null || export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
    echo 'eval "$(pyenv init -)"' >> ~/.bashrc
  3. Reload your shell: Close and reopen your terminal, or run exec "$SHELL".

3. Install a Python Version

With pyenv ready, you can install any version of Python.

  1. Install Python: Let's install the latest stable version (e.g., 3.12.2).
    pyenv install 3.12.2
  2. Set the global default:
    pyenv global 3.12.2
  3. Verify: python --version should now show 3.12.2.

4. Create a Virtual Environment (venv)

Never install packages globally. Always create an isolated environment for each project.

  1. Create a project folder: mkdir my-python-project && cd my-python-project
  2. Create the environment:
    python -m venv .venv

    (This creates a hidden .venv folder containing a copy of Python and pip).

  3. Activate the environment:
    source .venv/bin/activate

    Your terminal prompt will now change to show (.venv).

5. Install Packages with pip

Now that you are "inside" the virtual environment, you can safely install packages.

  • Install a package: pip install requests
  • Save dependencies: pip freeze > requirements.txt
  • Install from a list: pip install -r requirements.txt

To leave the environment, simply type deactivate.