Platform agnostic command and shell execution tool with timeout handling, live output capture, and UAC/sudo privilege elevation
npx @tessl/cli install tessl/pypi-command-runner@1.7.00
# Command Runner
1
2
A comprehensive platform-agnostic command execution library that serves as an enhanced replacement for subprocess.popen and subprocess.check_output. It provides robust handling of command timeouts, encoding issues, and platform differences between Windows and Linux/Unix systems, along with advanced features like live output capture, privilege elevation, and process management.
3
4
## Package Information
5
6
- **Package Name**: command_runner
7
- **Package Type**: pypi
8
- **Language**: Python
9
- **Installation**: `pip install command_runner`
10
- **Python Compatibility**: 2.7+
11
- **Platform Support**: Windows, Linux, macOS, Unix
12
13
## Core Imports
14
15
```python
16
from command_runner import command_runner
17
```
18
19
For threaded execution (Python 3+ only):
20
21
```python
22
from command_runner import command_runner_threaded
23
```
24
25
For privilege elevation:
26
27
```python
28
from command_runner.elevate import elevate
29
```
30
31
## Basic Usage
32
33
```python
34
from command_runner import command_runner
35
36
# Simple command execution
37
exit_code, output = command_runner('ping 127.0.0.1', timeout=10)
38
print(f"Exit code: {exit_code}")
39
print(f"Output: {output}")
40
41
# Cross-platform command execution
42
if os.name == 'nt':
43
cmd = 'ping 127.0.0.1 -n 4'
44
else:
45
cmd = ['ping', '-c', '4', '127.0.0.1']
46
47
exit_code, output = command_runner(cmd, encoding='utf-8')
48
```
49
50
## Architecture
51
52
Command Runner is built around a flexible execution framework:
53
54
- **Main Function**: `command_runner()` provides the primary interface with extensive configuration options
55
- **Execution Methods**: Two capture methods (monitor/poller) for different performance and feature trade-offs
56
- **Stream Handling**: Sophisticated output redirection supporting files, queues, callbacks, and live display
57
- **Process Management**: Complete process tree control with priority setting and reliable termination
58
- **Platform Abstraction**: Unified interface handling Windows/Unix differences transparently
59
- **Error Handling**: Comprehensive exception handling with consistent exit codes and partial output recovery
60
61
## Capabilities
62
63
### Core Command Execution
64
65
Primary command execution functionality with comprehensive timeout handling, encoding support, and output capture. Handles both string and list command formats across platforms with extensive configuration options.
66
67
```python { .api }
68
def command_runner(
69
command, # Union[str, List[str]] - Command to execute
70
valid_exit_codes=False, # Union[List[int], bool] - Accepted exit codes
71
timeout=3600, # Optional[int] - Timeout in seconds
72
shell=False, # bool - Use shell execution
73
encoding=None, # Optional[Union[str, bool]] - Output encoding
74
stdin=None, # Optional[Union[int, str, Callable, queue.Queue]]
75
stdout=None, # Optional[Union[int, str, Callable, queue.Queue]]
76
stderr=None, # Optional[Union[int, str, Callable, queue.Queue]]
77
no_close_queues=False, # Optional[bool] - Keep queues open
78
windows_no_window=False, # bool - Hide window on Windows
79
live_output=False, # bool - Show output during execution
80
method="monitor", # str - Capture method ("monitor" or "poller")
81
check_interval=0.05, # float - Polling interval
82
stop_on=None, # Callable - Custom stop condition
83
on_exit=None, # Callable - Exit callback
84
process_callback=None, # Callable - Process info callback
85
split_streams=False, # bool - Return separate stdout/stderr
86
silent=False, # bool - Suppress logging
87
priority=None, # Union[int, str] - Process priority
88
io_priority=None, # str - IO priority
89
heartbeat=0, # int - Heartbeat logging interval
90
**kwargs # Any - Additional subprocess arguments
91
):
92
"""
93
Execute commands with advanced timeout, encoding, and output handling.
94
95
Returns:
96
Union[Tuple[int, Optional[Union[bytes, str]]],
97
Tuple[int, Optional[Union[bytes, str]], Optional[Union[bytes, str]]]]
98
"""
99
```
100
101
```python { .api }
102
def command_runner_threaded(*args, **kwargs):
103
"""
104
Threaded version returning concurrent.Future result (Python 3+ only).
105
106
Returns:
107
concurrent.futures.Future
108
"""
109
```
110
111
[Core Command Execution](./core-execution.md)
112
113
### Process Management
114
115
Process priority control and reliable process tree termination functionality. Includes cross-platform priority setting and comprehensive child process management.
116
117
```python { .api }
118
def set_priority(pid, priority):
119
"""
120
Set process priority.
121
122
Args:
123
pid (int): Process ID
124
priority (Union[int, str]): Priority level
125
"""
126
127
def set_io_priority(pid, priority):
128
"""
129
Set IO priority.
130
131
Args:
132
pid (int): Process ID
133
priority (str): IO priority level
134
"""
135
136
def kill_childs_mod(pid=None, itself=False, soft_kill=False):
137
"""
138
Kill all children of a process.
139
140
Args:
141
pid (int, optional): Target process ID
142
itself (bool): Kill parent process too
143
soft_kill (bool): Use soft termination
144
145
Returns:
146
bool: Success status
147
"""
148
```
149
150
[Process Management](./process-management.md)
151
152
### Privilege Elevation
153
154
UAC/sudo elevation functionality compatible with CPython, Nuitka, PyInstaller, and other Python packaging systems. Provides seamless privilege escalation across Windows and Unix platforms.
155
156
```python { .api }
157
def elevate(callable_function, *args, **kwargs):
158
"""
159
Elevate privileges and execute function with admin/root rights.
160
161
Args:
162
callable_function: Function to execute with elevation
163
*args: Arguments to pass to function
164
**kwargs: Keyword arguments to pass to function
165
"""
166
167
def is_admin():
168
"""
169
Check if current process has administrative privileges.
170
171
Returns:
172
bool: True if admin privileges present
173
"""
174
```
175
176
[Privilege Elevation](./privilege-elevation.md)
177
178
### Utility Functions
179
180
Helper functions for encoding conversion, command preparation, and system compatibility. Includes constants for priority levels and platform-specific configurations.
181
182
```python { .api }
183
def to_encoding(process_output, encoding, errors):
184
"""
185
Convert bytes output to string with error handling.
186
187
Args:
188
process_output (Union[str, bytes]): Process output
189
encoding (Optional[str]): Target encoding
190
errors (str): Error handling strategy
191
192
Returns:
193
str: Converted string output
194
"""
195
196
def deferred_command(command, defer_time=300):
197
"""
198
Launch detached command with delay.
199
200
Args:
201
command (str): Command to execute
202
defer_time (int): Delay in seconds
203
"""
204
```
205
206
[Utility Functions](./utilities.md)
207
208
## Constants and Types
209
210
```python { .api }
211
# Subprocess pipe reference
212
PIPE = subprocess.PIPE
213
214
# Priority level mappings (platform-specific)
215
PRIORITIES = {
216
"process": {
217
"verylow": ...,
218
"low": ...,
219
"normal": ...,
220
"high": ...,
221
"rt": ...
222
},
223
"io": {
224
"low": ...,
225
"normal": ...,
226
"high": ...
227
}
228
}
229
230
# Special exit codes
231
# -250: Incompatible arguments
232
# -251: stop_on function returned True
233
# -252: KeyboardInterrupt
234
# -253: FileNotFoundError, OSError, IOError
235
# -254: Timeout
236
# -255: Uncaught exceptions
237
```
238
239
## Exception Classes
240
241
```python { .api }
242
class TimeoutExpired(BaseException):
243
"""Command timeout exception."""
244
def __init__(self, cmd, timeout, output=None, stderr=None): ...
245
246
class InterruptGetOutput(BaseException):
247
"""Base class for output capture on interruption."""
248
def __init__(self, output): ...
249
250
class KbdInterruptGetOutput(InterruptGetOutput):
251
"""Keyboard interrupt with output capture."""
252
253
class StopOnInterrupt(InterruptGetOutput):
254
"""Stop condition interrupt with output capture."""
255
```