Skip to content
Portfolio

Python Virtual Environments

In Python, running pip install saves dependencies globally on your operating system by default. This can cause conflicts when different projects require different versions of the same library.

The solution to this problem is creating virtual environments. A virtual environment (venv) is a self-contained directory that acts as a secure bubble holding its own isolated Python binary and local dependencies.

Terminal window
python3 -m venv .venv

Creates a hidden .venv folder containing the isolated Python environment.

Terminal window
source .venv/bin/activate
Terminal window
pip install requests paramiko

Python does not auto-generate a dependency file. You must manually export your exact dependency tree to a plain text file named requirements.txt:

Terminal window
pip freeze > requirements.txt

To replicate the exact environment on a production server:

Terminal window
pip install -r requirements.txt
Terminal window
deactivate

Change to the project directory, then run:

Terminal window
source .venv/bin/activate

To use a specific Python version for your project even if it is not installed on your machine, you can use a tool called pyenv.

On macOS:

Terminal window
brew install pyenv

On Linux, follow the pyenv installation guide.

Terminal window
pyenv install 3.11.8

3.3 Configure that version in your current directory

Section titled “3.3 Configure that version in your current directory”
Terminal window
pyenv local 3.11.8
Terminal window
python -m venv .venv