CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-command-runner

Platform agnostic command and shell execution tool with timeout handling, live output capture, and UAC/sudo privilege elevation

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

process-management.mddocs/

Process Management

Comprehensive process control functionality including priority management and reliable process tree termination. Provides cross-platform process management with optional psutil integration for enhanced capabilities.

Capabilities

Process Priority Control

Set CPU and IO priority levels for processes to optimize system resource usage and performance characteristics.

def set_priority(pid, priority):
    """
    Set process CPU priority level.
    
    Adjusts the CPU scheduling priority of the specified process. Uses platform-native
    priority systems (Windows priority classes, Unix nice values) with a unified interface.
    
    Args:
        pid (int): Process ID to modify
        priority (Union[int, str]): Priority level specification
            String values (cross-platform): "verylow", "low", "normal", "high", "rt"
            Int values (Unix only): -20 (highest) to 20 (lowest)
            
    Raises:
        ValueError: If priority value is invalid for the platform
        psutil.AccessDenied: If insufficient privileges to change priority
        psutil.NoSuchProcess: If process ID doesn't exist
        
    Examples:
        Set high priority for important process:
        >>> set_priority(1234, "high")
        
        Set background/low priority:
        >>> set_priority(1234, "low") 
        
        Unix-specific nice value:
        >>> set_priority(1234, -10)  # Higher than normal priority
        
    Platform Notes:
        Windows: Uses process priority classes (IDLE, BELOW_NORMAL, NORMAL, HIGH, REALTIME)
        Unix/Linux: Uses nice values mapped to priority strings
        macOS: Uses nice values with BSD-style priority handling
    """

def set_io_priority(pid, priority):
    """
    Set process IO priority level.
    
    Controls the IO scheduling priority for disk and network operations.
    Requires psutil module for full functionality.
    
    Args:
        pid (int): Process ID to modify  
        priority (str): IO priority level
            Values: "low", "normal", "high"
            
    Raises:
        ValueError: If priority value is not recognized
        psutil.AccessDenied: If insufficient privileges
        psutil.NoSuchProcess: If process ID doesn't exist
        NameError: If psutil module not available
        
    Examples:
        Set low IO priority for background tasks:
        >>> set_io_priority(1234, "low")
        
        Boost IO priority for time-critical operations:
        >>> set_io_priority(1234, "high")
        
    Platform Notes:
        Windows: Uses IO priority classes (LOW, NORMAL, HIGH)  
        Linux: Uses ionice scheduling classes (IDLE, BEST_EFFORT, REALTIME)
        macOS: Limited support through nice values
    """

Process Tree Termination

Reliable termination of process trees including all child processes. Handles platform differences in process hierarchy and provides both soft and hard termination options.

def kill_childs_mod(pid=None, itself=False, soft_kill=False):
    """
    Kill all child processes of a given process ID.
    
    Recursively terminates all descendant processes, handling platform differences
    in process tree management. Provides options for graceful vs forceful termination.
    
    Args:
        pid (int, optional): Target process ID. If None, uses current process ID.
        itself (bool): Whether to kill the parent process after children (default: False)
        soft_kill (bool): Use graceful termination (SIGTERM) vs forceful (SIGKILL) (default: False)
        
    Returns:
        bool: True if operation completed successfully, False if target process not found
        
    Raises:
        OSError: If process termination fails due to system-level errors
        
    Examples:
        Kill all children of current process:
        >>> kill_childs_mod()
        
        Kill process tree including parent:
        >>> kill_childs_mod(1234, itself=True)
        
        Graceful shutdown of process tree:
        >>> kill_childs_mod(1234, soft_kill=True)
        
        Emergency cleanup on exit:
        >>> import atexit, os
        >>> atexit.register(kill_childs_mod, os.getpid(), True)
        
    Platform Notes:
        Windows: Uses process walking since Windows lacks native process trees.
                May miss orphaned processes if parent died unexpectedly.
                Falls back to taskkill command for stubborn processes.
        Unix/Linux: Uses process group and parent-child relationships.
                   Supports both SIGTERM (soft) and SIGKILL (hard) signals.
        
    Implementation Details:
        - Prefers signal-based termination to avoid PID reuse race conditions
        - Handles missing psutil module gracefully with reduced functionality
        - Uses recursive termination to handle deeply nested process trees
        - Provides fallback mechanisms for platform-specific edge cases
    """

Priority Level Mappings

The priority system provides a unified interface across platforms while respecting platform-specific capabilities:

Process Priority Levels

# Cross-platform priority level mappings
PRIORITIES = {
    "process": {
        "verylow": ...,    # Idle/background priority
        "low": ...,        # Below normal priority  
        "normal": ...,     # Default system priority
        "high": ...,       # Above normal priority
        "rt": ...          # Real-time priority (use carefully)
    },
    "io": {
        "low": ...,        # Background IO operations
        "normal": ...,     # Standard IO priority
        "high": ...        # High-priority IO operations
    }
}

Platform-Specific Priority Constants

Windows Priority Classes:

  • IDLE_PRIORITY_CLASS: Very low priority (verylow)
  • BELOW_NORMAL_PRIORITY_CLASS: Below normal priority (low)
  • NORMAL_PRIORITY_CLASS: Standard priority (normal)
  • HIGH_PRIORITY_CLASS: High priority (high)
  • REALTIME_PRIORITY_CLASS: Real-time priority (rt)

Windows IO Priority Classes:

  • IOPRIO_LOW: Low IO priority
  • IOPRIO_NORMAL: Normal IO priority
  • IOPRIO_HIGH: High IO priority

Unix Priority Classes:

  • Nice values: -20 (highest) to 20 (lowest)
  • IOPRIO_CLASS_IDLE: Idle IO scheduling
  • IOPRIO_CLASS_BE: Best-effort IO scheduling
  • IOPRIO_CLASS_RT: Real-time IO scheduling

Usage Patterns

Automatic Priority Management

Command Runner can automatically set process priority during command execution:

from command_runner import command_runner

# Run command with low priority
exit_code, output = command_runner(
    'long_running_task', 
    priority='low',
    io_priority='low'
)

Manual Process Control

For more granular control, manage process priorities manually:

import os
from command_runner import set_priority, set_io_priority

# Get current process ID
pid = os.getpid()

# Set high CPU priority for critical section
set_priority(pid, 'high')

# Perform critical work
# ...

# Reset to normal priority
set_priority(pid, 'normal')

Process Tree Cleanup

Ensure reliable cleanup of spawned processes:

import os
import atexit
from command_runner import kill_childs_mod

# Register cleanup handler
atexit.register(kill_childs_mod, os.getpid(), True)

# Or manual cleanup
def cleanup_processes():
    kill_childs_mod(soft_kill=True)  # Try graceful first
    time.sleep(2)
    kill_childs_mod(soft_kill=False)  # Force kill if needed

Error Handling

Process management functions provide detailed error information:

Common Exceptions

  • psutil.AccessDenied: Insufficient privileges for operation
  • psutil.NoSuchProcess: Target process no longer exists
  • ValueError: Invalid priority value or argument
  • OSError: System-level operation failure
  • NameError: psutil module not available (limited functionality)

Best Practices

  1. Check Process Existence: Verify process still exists before priority changes
  2. Handle Privileges: Run with appropriate privileges for priority changes
  3. Graceful Degradation: Handle missing psutil module gracefully
  4. Error Recovery: Implement fallback strategies for failed operations
  5. Resource Cleanup: Always clean up child processes to prevent resource leaks

Dependencies

Required

  • Python standard library (os, subprocess, signal)

Optional

  • psutil: Enhanced process management capabilities
    • Required for IO priority setting
    • Required for reliable process tree termination
    • Provides more robust priority management
    • Installation: pip install psutil

Platform-Specific

  • Windows: win32process, win32api (for advanced features)
  • Unix/Linux: Standard POSIX process management
  • macOS: BSD-style process handling

Install with Tessl CLI

npx tessl i tessl/pypi-command-runner

docs

core-execution.md

index.md

privilege-elevation.md

process-management.md

utilities.md

tile.json