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.
1. Configuration (for Linux and macOS)
Section titled “1. Configuration (for Linux and macOS)”1.1 Create the environment
Section titled “1.1 Create the environment”python3 -m venv .venvCreates a hidden .venv folder containing the isolated Python environment.
1.2 Activate the environment
Section titled “1.2 Activate the environment”source .venv/bin/activate1.3 Install packages
Section titled “1.3 Install packages”pip install requests paramiko1.4 Save dependencies
Section titled “1.4 Save dependencies”Python does not auto-generate a dependency file. You must manually export your exact dependency tree to a plain text file named requirements.txt:
pip freeze > requirements.txtTo replicate the exact environment on a production server:
pip install -r requirements.txt2. How to switch environments
Section titled “2. How to switch environments”2.1 Deactivate the current environment
Section titled “2.1 Deactivate the current environment”deactivate2.2 Activate the new environment
Section titled “2.2 Activate the new environment”Change to the project directory, then run:
source .venv/bin/activate3. Specify the Python version
Section titled “3. Specify the Python version”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.
3.1 Install pyenv
Section titled “3.1 Install pyenv”On macOS:
brew install pyenvOn Linux, follow the pyenv installation guide.
3.2 Download the Python version you need
Section titled “3.2 Download the Python version you need”pyenv install 3.11.83.3 Configure that version in your current directory
Section titled “3.3 Configure that version in your current directory”pyenv local 3.11.83.4 Create the virtual environment
Section titled “3.4 Create the virtual environment”python -m venv .venv