PythonJune 29, 2025

Python Virtual Environment Helpers

Functions to create, activate, upgrade, deactivate, and remove Python virtual environments.

Each entry keeps the writeup and source together, so the page reads like a clipped page from the archive rather than a detached utility screen.

The implementation

The detail page preserves the practical behavior of the original route: the writeup stays readable, the source remains copyable and syntax highlighted, and the item can still link back into the rest of the catalog.

venv-helpers.sh
1# Add to ~/.bashrc or ~/.zshrc
2
3# Create and activate a Python virtual environment
4venv() {
5    local env_name="${1:-venv}"
6    
7    if [ -d "$env_name" ]; then
8        echo "Activating existing environment: $env_name"
9        source "$env_name/bin/activate"
10    else
11        echo "Creating new environment: $env_name"
12        python3 -m venv "$env_name"
13        source "$env_name/bin/activate"
14        pip install --upgrade pip
15    fi
16}
17
18# Deactivate and remove virtual environment
19venv-remove() {
20    local env_name="${1:-venv}"
21    
22    if [ -n "$VIRTUAL_ENV" ]; then
23        deactivate
24    fi
25    
26    if [ -d "$env_name" ]; then
27        rm -rf "$env_name"
28        echo "Removed environment: $env_name"
29    else
30        echo "Environment not found: $env_name"
31    fi
32}

More from the lab

Related utilities

View full catalog