0
# Command Execution
1
2
Core functionality for executing system commands with comprehensive process control, argument handling, and execution modes. Commands can be executed in foreground, background, or interactive modes with extensive configuration options.
3
4
## Capabilities
5
6
### Basic Command Execution
7
8
Execute system commands by calling Command objects as functions, with arguments passed as function parameters.
9
10
```python { .api }
11
def __call__(self, *args, **kwargs):
12
"""
13
Execute the command with given arguments.
14
15
Parameters:
16
- *args: Command arguments (strings, numbers, or Path objects)
17
- **kwargs: Execution options and special parameters
18
19
Returns:
20
str: Command output (stdout) for foreground execution
21
RunningCommand: Process object for background execution (_bg=True)
22
"""
23
```
24
25
Usage examples:
26
27
```python
28
import sh
29
30
# Basic command execution
31
output = sh.ls("-la", "/tmp")
32
print(output)
33
34
# Pass arguments as separate parameters
35
sh.git("add", ".")
36
sh.git("commit", "-m", "Initial commit")
37
38
# Mix different argument types
39
from pathlib import Path
40
sh.cp("file.txt", Path("/backup/"))
41
```
42
43
### Pre-configured Commands (Baking)
44
45
Create pre-configured Command objects with default arguments and options, useful for commands that need consistent parameters.
46
47
```python { .api }
48
def bake(self, *args, **kwargs):
49
"""
50
Create a new Command with pre-configured arguments.
51
52
Parameters:
53
- *args: Default arguments to include in all executions
54
- **kwargs: Default execution options
55
56
Returns:
57
Command: New Command object with baked-in arguments
58
"""
59
```
60
61
Usage examples:
62
63
```python
64
import sh
65
66
# Create pre-configured commands
67
ls_long = sh.ls.bake("-la")
68
git_log = sh.git.bake("log", "--oneline")
69
70
# Use pre-configured commands
71
output1 = ls_long("/tmp") # Equivalent to ls("-la", "/tmp")
72
output2 = ls_long("/home") # Equivalent to ls("-la", "/home")
73
74
commits = git_log("-10") # Equivalent to git("log", "--oneline", "-10")
75
76
# Bake with execution options
77
docker_exec = sh.docker.bake("exec", _tty=True, _env={"TERM": "xterm"})
78
result = docker_exec("container_name", "bash")
79
```
80
81
### Background Execution
82
83
Execute commands asynchronously in the background, allowing the Python script to continue while the command runs.
84
85
```python { .api }
86
def __call__(self, *args, _bg=True, **kwargs):
87
"""
88
Execute command in background.
89
90
Parameters:
91
- _bg: bool = True to run in background
92
93
Returns:
94
RunningCommand: Process object for monitoring and control
95
"""
96
```
97
98
Usage examples:
99
100
```python
101
import sh
102
import time
103
104
# Start command in background
105
proc = sh.sleep(10, _bg=True)
106
print("Command started, continuing...")
107
108
# Do other work while command runs
109
time.sleep(2)
110
print(f"Command still running: {proc.is_alive()}")
111
112
# Wait for completion
113
proc.wait()
114
print("Command completed")
115
116
# Multiple background processes
117
procs = []
118
for i in range(5):
119
proc = sh.ping("-c", "5", f"host{i}.example.com", _bg=True)
120
procs.append(proc)
121
122
# Wait for all to complete
123
for proc in procs:
124
proc.wait()
125
print(f"Ping completed with exit code: {proc.exit_code}")
126
```
127
128
### Interactive Execution
129
130
Execute commands with TTY allocation for interactive programs that require terminal input/output.
131
132
```python { .api }
133
def __call__(self, *args, _tty=True, **kwargs):
134
"""
135
Execute command with TTY allocation.
136
137
Parameters:
138
- _tty: bool = True to allocate a TTY
139
140
Returns:
141
str: Command output
142
"""
143
```
144
145
Usage examples:
146
147
```python
148
import sh
149
150
# Interactive commands requiring TTY
151
sh.vi("file.txt", _tty=True)
152
sh.less("/var/log/syslog", _tty=True)
153
154
# Docker containers with interactive shell
155
sh.docker("run", "-it", "ubuntu", "bash", _tty=True)
156
157
# SSH sessions
158
sh.ssh("user@server", _tty=True)
159
```
160
161
### Command Discovery and Validation
162
163
Check for command availability and get command information before execution.
164
165
```python { .api }
166
class Command:
167
def __str__(self) -> str:
168
"""String representation showing executable path and baked arguments."""
169
170
def __repr__(self) -> str:
171
"""Formal string representation of the Command object."""
172
```
173
174
Usage examples:
175
176
```python
177
import sh
178
179
# Check if command exists
180
try:
181
git_cmd = sh.Command("git")
182
print(f"Git command: {str(git_cmd)}")
183
except sh.CommandNotFound:
184
print("Git not installed")
185
186
# Dynamic command discovery
187
commands_to_check = ["docker", "kubectl", "helm"]
188
available = []
189
190
for cmd_name in commands_to_check:
191
try:
192
cmd = sh.Command(cmd_name)
193
available.append(cmd_name)
194
print(f"{cmd_name}: {str(cmd)}")
195
except sh.CommandNotFound:
196
print(f"{cmd_name}: not found")
197
```
198
199
### Execution Options
200
201
Various execution options can be specified as keyword arguments to control command behavior.
202
203
```python { .api }
204
def __call__(self, *args,
205
_bg=False, # Background execution
206
_tty=False, # TTY allocation
207
_cwd=None, # Working directory
208
_env=None, # Environment variables
209
_timeout=None, # Execution timeout
210
_ok_code=None, # Expected exit codes
211
**kwargs):
212
"""Execute command with options."""
213
```
214
215
Usage examples:
216
217
```python
218
import sh
219
import os
220
221
# Change working directory
222
output = sh.ls(_cwd="/tmp")
223
224
# Set environment variables
225
result = sh.env(_env={"MY_VAR": "value", "PATH": os.environ["PATH"]})
226
227
# Set timeout
228
try:
229
sh.sleep(60, _timeout=10) # Will timeout after 10 seconds
230
except sh.TimeoutException:
231
print("Command timed out")
232
233
# Accept different exit codes as success
234
try:
235
sh.grep("pattern", "file.txt", _ok_code=[0, 1]) # 0=found, 1=not found
236
except sh.ErrorReturnCode:
237
print("Unexpected error occurred")
238
```