Platform agnostic command and shell execution tool with timeout handling, live output capture, and UAC/sudo privilege elevation
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Comprehensive process control functionality including priority management and reliable process tree termination. Provides cross-platform process management with optional psutil integration for enhanced capabilities.
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
"""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
"""The priority system provides a unified interface across platforms while respecting platform-specific capabilities:
# 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
}
}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 priorityIOPRIO_NORMAL: Normal IO priorityIOPRIO_HIGH: High IO priorityUnix Priority Classes:
IOPRIO_CLASS_IDLE: Idle IO schedulingIOPRIO_CLASS_BE: Best-effort IO schedulingIOPRIO_CLASS_RT: Real-time IO schedulingCommand 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'
)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')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 neededProcess management functions provide detailed error information:
psutil.AccessDenied: Insufficient privileges for operationpsutil.NoSuchProcess: Target process no longer existsValueError: Invalid priority value or argumentOSError: System-level operation failureNameError: psutil module not available (limited functionality)pip install psutilInstall with Tessl CLI
npx tessl i tessl/pypi-command-runner