CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pip

The PyPA recommended tool for installing Python packages.

91

1.07x
Overview
Eval results
Files

configuration.mddocs/

Configuration and Environment

Comprehensive configuration management, environment inspection, caching control, and package index operations for customized pip workflows.

Capabilities

Help and Completion Utilities

Get help information and enable shell command completion for pip commands.

# Show general help
pip help

# Show help for specific command
pip help install
pip help uninstall

# Generate completion script for bash
pip completion --bash

# Generate completion script for zsh  
pip completion --zsh

# Generate completion script for fish
pip completion --fish

Configuration Management

Manage pip configuration at global, user, and site levels with hierarchical settings.

# List all configuration
pip config list

# List configuration for specific scope
pip config --global list
pip config --user list  
pip config --site list

# Get specific configuration value
pip config get global.index-url
pip config get install.user

# Set configuration values
pip config set global.index-url https://pypi.org/simple/
pip config set install.user true
pip config set global.timeout 60

# Unset configuration values
pip config unset global.index-url
pip config unset install.user

# Edit configuration file directly
pip config edit --global
pip config edit --user
pip config edit --site

Configuration hierarchy (highest to lowest priority):

  1. Command-line options (--index-url)
  2. Environment variables (PIP_INDEX_URL)
  3. User configuration file
  4. Global configuration file
  5. Site configuration file

Configuration file locations:

# Global configuration
# Unix: /etc/pip.conf
# Windows: C:\ProgramData\pip\pip.ini

# User configuration  
# Unix: ~/.config/pip/pip.conf or ~/.pip/pip.conf
# Windows: %APPDATA%\pip\pip.ini

# Site configuration
# Unix: $VIRTUAL_ENV/pip.conf
# Windows: %VIRTUAL_ENV%\pip.ini

Environment Variables

Control pip behavior through comprehensive environment variable configuration.

# Index and repository configuration
export PIP_INDEX_URL=https://pypi.org/simple/
export PIP_EXTRA_INDEX_URL=https://test.pypi.org/simple/
export PIP_TRUSTED_HOST="pypi.org test.pypi.org"
export PIP_FIND_LINKS=/path/to/local/packages

# Installation behavior
export PIP_USER=1                    # User installation
export PIP_REQUIRE_VIRTUALENV=1     # Require virtual environment
export PIP_NO_DEPS=1               # Skip dependencies
export PIP_UPGRADE=1                # Always upgrade
export PIP_FORCE_REINSTALL=1       # Force reinstall

# Build and binary options
export PIP_NO_BINARY=":all:"        # Build from source
export PIP_ONLY_BINARY=":all:"      # Only use wheels
export PIP_PREFER_BINARY=1          # Prefer binary packages
export PIP_NO_BUILD_ISOLATION=1     # Disable build isolation

# Caching and storage
export PIP_NO_CACHE_DIR=1           # Disable cache
export PIP_CACHE_DIR=/path/to/cache # Custom cache directory

# Network and timeouts
export PIP_TIMEOUT=60               # Connection timeout
export PIP_RETRIES=3                # Retry attempts
export PIP_PROXY=http://proxy:8080  # HTTP proxy
export PIP_CERT=/path/to/cert.pem   # SSL certificate

# Output and logging
export PIP_QUIET=1                  # Minimal output
export PIP_VERBOSE=1                # Verbose output
export PIP_LOG_FILE=/path/to/pip.log # Log file
export PIP_NO_COLOR=1               # Disable colored output

Configuration File Format

Configuration files use INI format with section-based organization.

# Global pip configuration file
[global]
index-url = https://pypi.org/simple/
extra-index-url = https://test.pypi.org/simple/
trusted-host = pypi.org
                test.pypi.org
timeout = 60
retries = 3

[install]
user = true
upgrade = true
find-links = /path/to/local/packages

[freeze]
exclude = pip
          setuptools
          wheel

[list]
format = columns

[wheel]
wheel-dir = /path/to/wheels

[hash]
algorithm = sha256

Environment Inspection

Inspect Python environment, pip installation, and system information.

# Comprehensive environment inspection
pip inspect

# Debug information
pip debug

# Show pip version and location
pip --version

# Show configuration locations
pip config debug

Environment inspection provides:

  • Python interpreter information
  • Virtual environment details
  • Installation paths and prefix
  • Site packages directories
  • Platform and architecture information
  • Pip version and location
  • Configuration file locations
  • Installed packages with metadata

Cache Management

Control pip's wheel cache for improved performance and storage management.

# Show cache information
pip cache info

# List cached packages
pip cache list

# List cache for specific package
pip cache list package_name

# Remove all cached files
pip cache purge

# Remove cache for specific package
pip cache remove package_name

# Remove cache with pattern matching
pip cache remove "django*"

# Show cache directory
pip cache dir

Cache operations:

# Custom cache directory
pip install --cache-dir /custom/cache package_name

# Disable cache for specific operation
pip install --no-cache-dir package_name

# Environment variable for cache directory
export PIP_CACHE_DIR=/custom/cache

Index Operations

Inspect package information from package indexes without installation.

# Show available versions
pip index versions package_name

# Show versions from all configured indexes
pip index versions --pre package_name

# Show versions with extra index
pip index --extra-index-url https://test.pypi.org/simple/ versions package_name

Authentication and Security

Configure authentication for private repositories and security settings.

# Using netrc for authentication
# Create ~/.netrc (Unix) or ~/_netrc (Windows)
# machine pypi.org
# login username
# password token

# Using keyring for password storage
pip install keyring
keyring set https://pypi.org/simple/ username

# Basic authentication in URL
pip install --index-url https://username:password@private.pypi.org/simple/ package_name

# Token authentication
pip install --index-url https://token@private.pypi.org/simple/ package_name

# Client certificates
pip install --cert /path/to/client.pem --client-cert /path/to/client.key package_name

# Trusted hosts (disable SSL verification)
pip install --trusted-host private.pypi.org package_name

Proxy Configuration

Configure proxy settings for network environments.

# HTTP proxy
pip install --proxy http://proxy.company.com:8080 package_name

# HTTPS proxy
pip install --proxy https://proxy.company.com:8080 package_name

# Proxy with authentication
pip install --proxy http://user:password@proxy.company.com:8080 package_name

# No proxy for specific hosts
export NO_PROXY="localhost,127.0.0.1,.company.com"

# System proxy detection
# Pip automatically detects system proxy settings

Virtual Environment Integration

Configure pip behavior in virtual environments.

# Require virtual environment
pip config set global.require-virtualenv true
export PIP_REQUIRE_VIRTUALENV=1

# Detect virtual environment
python -c "import sys; print(hasattr(sys, 'real_prefix') or (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))"

# Virtual environment specific configuration
# Located at $VIRTUAL_ENV/pip.conf (Unix) or %VIRTUAL_ENV%\pip.ini (Windows)

Programmatic Configuration

Manage pip configuration programmatically through subprocess calls.

import subprocess
import sys
import os
from pathlib import Path

def get_config(key, scope='global'):
    """Get pip configuration value."""
    cmd = [sys.executable, '-m', 'pip', 'config', f'--{scope}', 'get', key]
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        return result.stdout.strip()
    except subprocess.CalledProcessError:
        return None

def set_config(key, value, scope='global'):
    """Set pip configuration value."""
    cmd = [sys.executable, '-m', 'pip', 'config', f'--{scope}', 'set', key, value]
    
    try:
        subprocess.check_call(cmd)
        print(f"Set {scope} config {key} = {value}")
    except subprocess.CalledProcessError as e:
        print(f"Failed to set config: {e}")
        raise

def list_config(scope=None):
    """List pip configuration."""
    cmd = [sys.executable, '-m', 'pip', 'config']
    if scope:
        cmd.append(f'--{scope}')
    cmd.append('list')
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Failed to list config: {e}")
        return None

def get_cache_info():
    """Get pip cache information."""
    cmd = [sys.executable, '-m', 'pip', 'cache', 'info']
    
    try:
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        return result.stdout
    except subprocess.CalledProcessError as e:
        print(f"Failed to get cache info: {e}")
        return None

def purge_cache():
    """Purge pip cache."""
    cmd = [sys.executable, '-m', 'pip', 'cache', 'purge']
    
    try:
        subprocess.check_call(cmd)
        print("Cache purged successfully")
    except subprocess.CalledProcessError as e:
        print(f"Failed to purge cache: {e}")
        raise

def setup_environment_config():
    """Set up comprehensive pip environment configuration."""
    # Index configuration
    os.environ['PIP_INDEX_URL'] = 'https://pypi.org/simple/'
    os.environ['PIP_TIMEOUT'] = '60'
    os.environ['PIP_RETRIES'] = '3'
    
    # Installation preferences
    os.environ['PIP_PREFER_BINARY'] = '1'
    os.environ['PIP_UPGRADE_STRATEGY'] = 'eager'
    
    # Cache configuration
    cache_dir = Path.home() / '.pip_cache'
    cache_dir.mkdir(exist_ok=True)
    os.environ['PIP_CACHE_DIR'] = str(cache_dir)
    
    print("Environment configuration set up")

def create_config_file(config_path, config_dict):
    """Create pip configuration file."""
    from configparser import ConfigParser
    
    config_path = Path(config_path)
    config_path.parent.mkdir(parents=True, exist_ok=True)
    
    config = ConfigParser()
    
    for section, values in config_dict.items():
        config.add_section(section)
        for key, value in values.items():
            config.set(section, key, str(value))
    
    with open(config_path, 'w') as f:
        config.write(f)
    
    print(f"Configuration file created at {config_path}")

# Usage examples
index_url = get_config('global.index-url')
print(f"Current index URL: {index_url}")

set_config('global.timeout', '60')
set_config('install.user', 'true', scope='user')

config_output = list_config()
print("Current configuration:")
print(config_output)

cache_info = get_cache_info()
print("Cache information:")
print(cache_info)

# Set up environment
setup_environment_config()

# Create custom configuration file
config_data = {
    'global': {
        'index-url': 'https://pypi.org/simple/',
        'timeout': 60,
        'retries': 3
    },
    'install': {
        'user': True,
        'upgrade': True
    }
}
create_config_file('~/.pip/pip.conf', config_data)

Advanced Configuration Patterns

Complex configuration scenarios and best practices.

import os
import subprocess
import sys
from pathlib import Path

class PipConfigManager:
    """Advanced pip configuration management."""
    
    def __init__(self):
        self.config_locations = self._get_config_locations()
    
    def _get_config_locations(self):
        """Get pip configuration file locations."""
        locations = {}
        
        if os.name == 'nt':  # Windows
            locations['global'] = Path(os.environ.get('PROGRAMDATA', '')) / 'pip' / 'pip.ini'
            locations['user'] = Path(os.environ['APPDATA']) / 'pip' / 'pip.ini'
        else:  # Unix-like
            locations['global'] = Path('/etc/pip.conf')
            locations['user'] = Path.home() / '.config' / 'pip' / 'pip.conf'
            # Also check legacy location
            legacy_user = Path.home() / '.pip' / 'pip.conf'
            if legacy_user.exists():
                locations['user'] = legacy_user
        
        # Virtual environment configuration
        venv_prefix = os.environ.get('VIRTUAL_ENV')
        if venv_prefix:
            if os.name == 'nt':
                locations['site'] = Path(venv_prefix) / 'pip.ini'
            else:
                locations['site'] = Path(venv_prefix) / 'pip.conf'
        
        return locations
    
    def setup_development_environment(self):
        """Set up pip configuration for development."""
        config = {
            'global': {
                'timeout': '60',
                'retries': '3',
                'prefer-binary': 'true'
            },
            'install': {
                'upgrade': 'true',
                'upgrade-strategy': 'eager'
            },
            'freeze': {
                'exclude': 'pip setuptools wheel'
            }
        }
        
        self._write_config('user', config)
        
        # Set environment variables
        os.environ.update({
            'PIP_CACHE_DIR': str(Path.home() / '.pip_cache'),
            'PIP_LOG_FILE': str(Path.home() / '.pip' / 'pip.log')
        })
    
    def setup_production_environment(self):
        """Set up pip configuration for production."""
        config = {
            'global': {
                'timeout': '30',
                'retries': '5',
                'only-binary': ':all:',
                'no-compile': 'true'
            },
            'install': {
                'require-hashes': 'true',
                'no-deps': 'false'
            }
        }
        
        self._write_config('site', config)
    
    def _write_config(self, scope, config_dict):
        """Write configuration to file."""
        from configparser import ConfigParser
        
        config_path = self.config_locations.get(scope)
        if not config_path:
            raise ValueError(f"Unknown scope: {scope}")
        
        config_path.parent.mkdir(parents=True, exist_ok=True)
        
        config = ConfigParser()
        for section, values in config_dict.items():
            config.add_section(section)
            for key, value in values.items():
                config.set(section, key, str(value))
        
        with open(config_path, 'w') as f:
            config.write(f)

# Usage
manager = PipConfigManager()
manager.setup_development_environment()

Install with Tessl CLI

npx tessl i tessl/pypi-pip

docs

building.md

configuration.md

index.md

installation.md

management.md

tile.json