CommandResult dataclass
Encapsulates the complete output, metadata, and execution context of a system command.
📖 Class Overview
CommandResult is a robust container that stores every aspect of a command execution lifecycle:
standard output, error streams, exit code, execution duration, and the original command arguments.
It provides intuitive methods to check success, parse JSON responses, and even supports pipe operators.
- Immutable-like fields for reliable state tracking
is_success()→ quick status validationjson()→ automatic JSON deserialization from stdout__or__→ native pipe support (|operator)
📋 Class Attributes
| Field | Type | Description |
|---|---|---|
standard_output |
str |
Captured output from the command's stdout stream. Default: "" |
standard_error |
str |
Captured error messages from the command's stderr stream. Default: "" |
return_code |
int |
The exit status code (0 usually indicates success). Default: 0 |
execution_time |
float |
Total duration of the command execution in seconds. Default: 0.0 |
command_sent |
list[str] |
The original command arguments sent for execution. Default: empty list [] |
⚙️ Public Methods
is_success() → bool
Returns True if the command executed successfully. The success condition is determined by the return code being exactly 0.
result.is_success() # True if return_code == 0
json() → Any
Parses the standard_output string as JSON and returns a Python object (dictionary, list, or primitive). Raises json.JSONDecodeError if the output is not valid JSON.
data = result.json() # automatically loads from stdout
🔗 Special Methods (Operator Overload)
__or__(self, next_command: Any) → str
Enables the pipe syntax (| operator). When used, it returns the raw standard_output string, allowing seamless chaining or forwarding to another process or function.
# Example: pipe result's output to another handler
output = command_result | some_processor # returns self.standard_output
Use case: Simulate shell-like piping between command results or simply extract stdout elegantly.
🚀 Usage Example
Below is a practical demonstration of how CommandResult behaves after executing a command (simulated).
from dataclasses import dataclass, field
import json
from typing import Any
# (Assuming CommandResult class is defined as above)
# Simulated instance:
cmd_result = CommandResult(
standard_output='{"status": "ok", "data": [1,2,3]}',
standard_error="",
return_code=0,
execution_time=0.234,
command_sent=["curl", "https://api.example.com"]
)
# 1. Check success
if cmd_result.is_success():
print("✅ Command succeeded")
# 2. Parse JSON response
parsed = cmd_result.json()
print(parsed["data"]) # [1,2,3]
# 3. Pipe operator usage (returns stdout string)
output_text = cmd_result | None # returns standard_output
print(output_text) # {"status": "ok", ...}
# 4. Access metadata
print(f"Duration: {cmd_result.execution_time}s, Cmd: {cmd_result.command_sent}")
✅ Command succeeded
[1, 2, 3]
{"status": "ok", "data": [1,2,3]}
Duration: 0.234s, Cmd: ['curl', 'https://api.example.com']
📌 Implementation Notes
- The class uses
field(default_factory=list)forcommand_sentto avoid mutable default issues — each instance gets a fresh list. execution_timeis measured in seconds (float), suitable for high-resolution timing.- The
json()method directly callsjson.loads()onstandard_output. Ensure the output contains valid JSON to avoid exceptions. __or__returns the raw string, making it easy to integrate with functions expecting text input.