Process Module¶
Process execution and result handling utilities for subprocess management.
Overview¶
The process module provides low-level utilities for executing subprocesses and handling their results. It wraps Python's subprocess module with a more convenient API and structured result objects.
Key Components:
ProcessResult- Structured result object containing exit code, stdout, stderr, and execution durationrun_process()- Execute a subprocess and return a ProcessResultensure_tool_available()- Verify an external tool is installed and accessible
Common Usage Patterns¶
Basic Process Execution¶
from shannot.process import run_process
# Simple execution
result = run_process(["ls", "-la", "/tmp"])
print(result.stdout)
# Check exit status
if result.succeeded():
print("Command succeeded")
else:
print(f"Failed with exit code {result.returncode}")
Error Handling¶
# Automatic error checking
try:
result = run_process(["false"], check=True)
except subprocess.CalledProcessError as e:
print(f"Command failed: {e}")
# Manual error checking
result = run_process(["cat", "/missing"], check=False)
if not result.succeeded():
print(f"Error: {result.stderr}")
print(f"Exit code: {result.returncode}")
Execution with Options¶
from pathlib import Path
# Custom working directory
result = run_process(
["pwd"],
cwd="/tmp"
)
# Custom environment
result = run_process(
["env"],
env={"CUSTOM_VAR": "value", "PATH": "/usr/bin"}
)
# Timeout
result = run_process(
["sleep", "10"],
timeout=5.0 # Raises TimeoutExpired after 5 seconds
)
# Print command before execution
result = run_process(
["ls", "/"],
print_command=True # Prints: + ls /
)
Tool Availability Checking¶
from shannot.process import ensure_tool_available
from pathlib import Path
# Check if a tool exists
try:
bwrap_path = ensure_tool_available("bwrap", search_path=True)
print(f"Found bwrap at: {bwrap_path}")
except FileNotFoundError as e:
print(f"Tool not found: {e}")
# Check specific path
ensure_tool_available(Path("/usr/bin/bwrap"), search_path=False)
Result Inspection¶
result = run_process(["du", "-sh", "/var/log"])
# Access result properties
print(f"Command: {' '.join(result.command)}")
print(f"Exit code: {result.returncode}")
print(f"Duration: {result.duration:.3f} seconds")
print(f"Output length: {len(result.stdout)} bytes")
# Check success
if result.succeeded():
for line in result.stdout.splitlines():
print(line)
Related Documentation¶
- Sandbox Module - Uses process utilities for command execution
- Execution Module - High-level execution interface
- Python API Guide - Integration examples
API Reference¶
process
¶
Classes¶
ProcessResult
dataclass
¶
Represents the outcome of a subprocess invocation.
Source code in shannot/process.py
Functions¶
run_process(args, *, cwd=None, env=None, check=False, capture_output=True, timeout=None, print_command=False)
¶
Execute args with subprocess.run and return a structured result.
Args:
args: Command and arguments to execute.
cwd: Optional working directory.
env: Optional environment overrides.
check: When True, re-raises CalledProcessError on non-zero exit.
capture_output: When True, captures stdout/stderr into the result.
timeout: Optional timeout in seconds.
print_command: When True, echoes the command before execution.
Returns: ProcessResult with stdout/stderr always normalised to text.
Source code in shannot/process.py
ensure_tool_available(executable)
¶
Ensure the given executable is present on PATH and return its resolved Path.