CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pip-upgrader

An interactive pip requirements upgrader that also updates the version in your requirements.txt file

Pending
Overview
Eval results
Files

environment-validation.mddocs/

Environment Validation

Virtual environment detection and validation to ensure packages are installed in the appropriate environment.

Capabilities

Virtual Environment Detection

Detects whether the current Python process is running within a virtual environment using multiple detection methods.

def is_virtualenv():
    """
    Check if currently running in a virtual environment.
    
    Returns:
        bool: True if running in a virtual environment
        
    Detection methods:
    1. sys.base_prefix vs sys.prefix comparison (venv, virtualenv)
    2. sys.real_prefix attribute existence (virtualenv)  
    3. VIRTUAL_ENV environment variable (conda, virtualenv)
    
    Compatibility:
    - Works with venv (Python 3.3+)
    - Works with virtualenv (all versions)
    - Works with conda environments
    - Cross-platform (Windows, macOS, Linux)
    """

Environment Validation

Validates virtual environment status and warns users when not in a virtual environment.

def check_for_virtualenv(options):
    """
    Check for virtualenv and warn if not activated.
    
    Args:
        options (dict): Command-line options containing:
            --skip-virtualenv-check (bool): Skip validation if True
            --skip-package-installation (bool): Skip validation if True
            
    Raises:
        KeyboardInterrupt: If not in virtualenv and checks are not skipped
        
    Warning behavior:
    - Displays colored warning message with recommendations
    - Suggests activating virtualenv or using skip options
    - Allows user to abort installation
    """

Detection Methods

Python 3.3+ venv Detection

Uses sys.base_prefix vs sys.prefix comparison:

import sys

# In regular Python: base_prefix == prefix
# In venv: base_prefix != prefix
if getattr(sys, 'base_prefix', sys.prefix) != sys.prefix:
    return True

Legacy virtualenv Detection

Checks for sys.real_prefix attribute:

import sys

# virtualenv sets sys.real_prefix
# Regular Python and venv don't have this attribute
if hasattr(sys, 'real_prefix'):
    return True

Environment Variable Detection

Checks VIRTUAL_ENV environment variable:

import os

# Set by virtualenv, venv, and conda
if os.environ.get('VIRTUAL_ENV'):
    return True

Validation Behavior

Normal Operation

When not in a virtual environment:

It seems you haven't activated a virtualenv.
Installing packages directly in the system is not recommended.
Activate your project's virtualenv, or re-run this command with one of the following options:
--skip-virtualenv-check (install the packages anyway)
--skip-package-installation (don't install any package. just update the requirements file(s))

Message features:

  • Yellow warning color using colorclass
  • Clear explanation of the issue
  • Specific recommendations for resolution
  • Magenta highlighting of option names

Skip Conditions

Validation is skipped when:

  1. --skip-virtualenv-check: Explicitly disable validation
  2. --skip-package-installation: No packages will be installed anyway
if options.get('--skip-virtualenv-check', False) or \
   options.get('--skip-package-installation', False):
    return  # No check needed

Usage Examples

Manual Environment Detection

from pip_upgrader.virtualenv_checker import is_virtualenv

# Check if in virtual environment
if is_virtualenv():
    print("Running in virtual environment")
else:
    print("Not in virtual environment")

Environment Validation

from pip_upgrader.virtualenv_checker import check_for_virtualenv

# Validate environment with standard options
options = {
    '--skip-virtualenv-check': False,
    '--skip-package-installation': False
}

try:
    check_for_virtualenv(options)
    print("Environment validation passed")
except KeyboardInterrupt:
    print("Environment validation failed or user cancelled")

Skip Validation

# Skip validation explicitly
options = {'--skip-virtualenv-check': True}
check_for_virtualenv(options)  # Returns immediately

# Skip validation when not installing packages
options = {'--skip-package-installation': True}
check_for_virtualenv(options)  # Returns immediately

Environment Types

Python venv (Python 3.3+)

Created with:

python -m venv myenv
source myenv/bin/activate  # Unix
myenv\Scripts\activate     # Windows

Detection characteristics:

  • sys.base_prefix != sys.prefix
  • VIRTUAL_ENV environment variable set
  • No sys.real_prefix attribute

virtualenv (Legacy)

Created with:

virtualenv myenv
source myenv/bin/activate  # Unix
myenv\Scripts\activate     # Windows

Detection characteristics:

  • sys.real_prefix attribute exists
  • VIRTUAL_ENV environment variable set
  • May also have sys.base_prefix != sys.prefix

Conda Environments

Created with:

conda create -n myenv python=3.9
conda activate myenv

Detection characteristics:

  • VIRTUAL_ENV environment variable set (usually)
  • May have CONDA_DEFAULT_ENV environment variable
  • Detection varies by conda version and configuration

System Python

Regular Python installation without virtual environment:

Detection characteristics:

  • sys.base_prefix == sys.prefix (if base_prefix exists)
  • No sys.real_prefix attribute
  • No VIRTUAL_ENV environment variable

Platform Compatibility

Windows

# Activation scripts
myenv\Scripts\activate.bat  # Command Prompt
myenv\Scripts\Activate.ps1  # PowerShell

# Detection works with Windows paths
VIRTUAL_ENV=C:\Users\user\myenv

Unix/Linux/macOS

# Activation script
source myenv/bin/activate

# Detection works with Unix paths  
VIRTUAL_ENV=/home/user/myenv

Cross-Platform Considerations

  • Path separators handled automatically by Python
  • Environment variable access works consistently
  • sys.prefix paths are platform-appropriate

Integration Points

CLI Integration

Called early in the main CLI workflow:

def main():
    options = get_options()
    Windows.enable(auto_colors=True, reset_atexit=True)
    
    try:
        # Virtual environment check happens first
        check_for_virtualenv(options)
        
        # Continue with requirements detection, etc.
        # ...
    except KeyboardInterrupt:
        print(Color('\n{autored}Upgrade interrupted.{/autored}'))

Error Flow

When validation fails:

  1. Display colored warning message
  2. Raise KeyboardInterrupt
  3. CLI catches exception and displays "Upgrade interrupted"
  4. Process exits cleanly

Skip Options

Two ways to bypass validation:

  1. --skip-virtualenv-check: User explicitly acknowledges system installation
  2. --skip-package-installation: No packages will be installed, so environment doesn't matter

Security Considerations

System Package Installation

Installing packages directly to system Python can:

  • Conflict with system packages
  • Require elevated privileges
  • Affect other applications
  • Create dependency conflicts

Virtual Environment Benefits

Virtual environments provide:

  • Isolated package installations
  • Project-specific dependency versions
  • No system-wide changes
  • Easy cleanup and recreation

Recommendation Logic

The validator recommends virtual environments because:

  • Safer for development workflows
  • Prevents system package conflicts
  • Follows Python best practices
  • Enables reproducible environments

Error Messages

Warning Message Format

{autoyellow}It seems you haven't activated a virtualenv.
Installing packages directly in the system is not recommended.
{automagenta}Activate your project's virtualenv{/automagenta}, or {automagenta}re-run this command{/automagenta} with one of the following options:
--skip-virtualenv-check (install the packages anyway)
--skip-package-installation (don't install any package. just update the requirements file(s)){/autoyellow}

Color coding:

  • Yellow: Main warning text
  • Magenta: Action items and option names
  • Clear structure with line breaks for readability

Install with Tessl CLI

npx tessl i tessl/pypi-pip-upgrader

docs

cli-interface.md

environment-validation.md

index.md

interactive-selection.md

package-parsing.md

package-upgrading.md

requirements-detection.md

status-detection.md

tile.json