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 forpyenvare 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.
- Run the installer:
curl https://pyenv.run | bash - Add to your shell: The script will output instructions to add
pyenvto your~/.bashrcfile. 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 - 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.
- Install Python: Let's install the latest stable version (e.g., 3.12.2).
pyenv install 3.12.2 - Set the global default:
pyenv global 3.12.2 - Verify:
python --versionshould now show3.12.2.
4. Create a Virtual Environment (venv)
Never install packages globally. Always create an isolated environment for each project.
- Create a project folder:
mkdir my-python-project && cd my-python-project - Create the environment:
python -m venv .venv(This creates a hidden
.venvfolder containing a copy of Python andpip). - Activate the environment:
source .venv/bin/activateYour 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.