bounded_subprocess
bounded_subprocess
Bounded subprocess execution with timeout and output limits.
This package provides convenient functions for running subprocesses with bounded execution time and output size, with support for both synchronous and asynchronous execution patterns.
bounded_subprocess.bounded_subprocess
Synchronous subprocess execution with bounds on runtime and output size.
run(args: List[str], timeout_seconds: int = 15, max_output_size: int = 2048, env=None, stdin_data: Optional[str] = None, stdin_write_timeout: Optional[int] = None) -> Result
Run a subprocess with a timeout and bounded stdout/stderr capture.
This helper starts the child in a new session so timeout cleanup can kill
the entire process group. Stdout and stderr are read in nonblocking mode and
truncated to max_output_size bytes each. If the timeout elapses, the
returned Result.timeout is True and Result.exit_code is -1. If
stdin_data cannot be fully written before stdin_write_timeout,
Result.exit_code is set to -1 even if the process exits normally.
Example:
from bounded_subprocess import run
result = run(
["bash", "-lc", "echo ok; echo err 1>&2"],
timeout_seconds=5,
max_output_size=1024,
)
print(result.exit_code)
print(result.stdout.strip())
print(result.stderr.strip())
Source code in src/bounded_subprocess/bounded_subprocess.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 | |
bounded_subprocess.bounded_subprocess_async
Asynchronous subprocess execution with bounds on runtime and output size.
podman_run(args: List[str], *, image: str, timeout_seconds: int, max_output_size: int, env=None, stdin_data: Optional[str] = None, stdin_write_timeout: Optional[int] = None, volumes: List[str] = [], cwd: Optional[str] = None, memory_limit_mb: Optional[int] = None) -> Result
async
Run a subprocess in a podman container asynchronously with bounded stdout/stderr capture.
This function wraps `run` but executes the command inside a podman container.
The container is automatically removed after execution. The interface is otherwise
the same as `run`, except for an additional `image` parameter to specify the
container image to use.
Args:
args: Command arguments to run in the container.
image: Container image to use.
timeout_seconds: Maximum time to wait for the process to complete.
max_output_size: Maximum size in bytes for stdout/stderr capture.
env: Optional dictionary of environment variables.
stdin_data: Optional string data to write to stdin.
stdin_write_timeout: Optional timeout for writing stdin data.
volumes: Optional list of volume mount specifications (e.g., ["/host/path:/container/path"]).
cwd: Optional working directory path inside the container.
memory_limit_mb: Optional memory limit in megabytes for the container.
Example:
```python
import asyncio
from bounded_subprocess.bounded_subprocess_async import podman_run
async def main():
result = await podman_run(
["cat"],
image="alpine:latest",
timeout_seconds=5,
max_output_size=1024,
stdin_data="hello
", volumes=["/host/data:/container/data"], cwd="/container/data", ) print(result.exit_code) print(result.stdout.strip())
asyncio.run(main())
```
Source code in src/bounded_subprocess/bounded_subprocess_async.py
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | |
run(args: List[str], timeout_seconds: int = 15, max_output_size: int = 2048, env=None, stdin_data: Optional[str] = None, stdin_write_timeout: Optional[int] = None, memory_limit_mb: Optional[int] = None, memory_watchdog_interval_seconds: float = 1.0) -> Result
async
Run a subprocess asynchronously with bounded stdout/stderr capture.
The child process is started in a new session and polled until it exits or
the timeout elapses. Stdout and stderr are read in nonblocking mode and
truncated to max_output_size bytes each. If the timeout elapses,
Result.timeout is True and Result.exit_code is -1. If stdin_data
cannot be fully written before stdin_write_timeout, Result.exit_code
is set to -1 even if the process exits normally. If memory_limit_mb is
set, a watchdog checks aggregate peak RSS (VmHWM, summed across the
process group) at a fixed interval and kills the process group when the
limit is exceeded.
Example:
import asyncio
from bounded_subprocess.bounded_subprocess_async import run
async def main():
result = await run(
["bash", "-lc", "echo ok; echo err 1>&2"],
timeout_seconds=5,
max_output_size=1024,
)
print(result.exit_code)
print(result.stdout.strip())
print(result.stderr.strip())
asyncio.run(main())
Source code in src/bounded_subprocess/bounded_subprocess_async.py
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
bounded_subprocess.interactive
Interactive subprocess wrapper with nonblocking stdin/stdout.
Interactive(args: List[str], read_buffer_size: int)
Interact with a subprocess using nonblocking I/O.
The subprocess is started with pipes for stdin and stdout. Writes are
bounded by a timeout, and reads return complete lines (without the trailing
newline). The internal buffer is capped at `read_buffer_size`; older bytes
are dropped if output grows without line breaks.
Example:
```python
from bounded_subprocess.interactive import Interactive
proc = Interactive(["python3", "-u", "-c", "print(input())"], read_buffer_size=4096)
ok = proc.write(b"hello
", timeout_seconds=1) line = proc.read_line(timeout_seconds=1) rc = proc.close(nice_timeout_seconds=1) ```
Start a subprocess with a bounded stdout buffer.
The child process is created with nonblocking stdin/stdout pipes. The
internal read buffer keeps at most read_buffer_size bytes of recent
output.
Source code in src/bounded_subprocess/interactive.py
close(nice_timeout_seconds: int) -> int
Close pipes, wait briefly, then kill the subprocess.
Returns the subprocess return code, or -9 if the process is still running when it is killed.
Source code in src/bounded_subprocess/interactive.py
read_line(timeout_seconds: int) -> Optional[bytes]
Read the next line from stdout, or return None on timeout/EOF.
The returned line does not include the trailing newline byte.
Source code in src/bounded_subprocess/interactive.py
write(stdin_data: bytes, timeout_seconds: int) -> bool
Write stdin_data to the subprocess within timeout_seconds.
Returns False if the subprocess has already exited or if writing fails.
Source code in src/bounded_subprocess/interactive.py
bounded_subprocess.util
Utilities for bounded subprocess I/O and nonblocking pipe helpers.
Result(timeout, exit_code, stdout, stderr)
dataclass
Result of a bounded subprocess run.
The stdout and stderr fields contain at most the requested number of
bytes, decoded with errors ignored. timeout is True only when the overall
timeout elapses. When a timeout or stdin write failure occurs, exit_code
is -1.
Source code in src/bounded_subprocess/util.py
can_read(fd)
async
Wait until the file descriptor is readable.
Source code in src/bounded_subprocess/util.py
can_write(fd)
async
Wait until the file descriptor is writable.
Source code in src/bounded_subprocess/util.py
read_to_eof_async(files: list, *, timeout_seconds: int, max_len: int) -> List[bytes]
async
Asynchronously read from nonblocking FDs until EOF or timeout.
The returned list preserves the order of the files argument.
Source code in src/bounded_subprocess/util.py
read_to_eof_sync(files: list, *, timeout_seconds: int, max_len: int) -> Optional[List[bytes]]
Read from nonblocking file descriptors until EOF, with limits on how long to wait and the maximum number of bytes to read.
Returns the data read, or None if the timeout elapsed.
Source code in src/bounded_subprocess/util.py
set_nonblocking(reader)
Mark a file descriptor as nonblocking.
This is required before using the read/write helpers that rely on nonblocking behavior.
Source code in src/bounded_subprocess/util.py
write_loop_sync(write_chunk: Callable[[memoryview], tuple[int, bool]], data: bytes, timeout_seconds: float, *, sleep_interval: float) -> bool
Repeatedly write data using write_chunk until complete or timeout.
The write_chunk callback returns (bytes_written, keep_going). If
keep_going is False, this function returns False immediately.
Source code in src/bounded_subprocess/util.py
write_nonblocking_async(*, fd, data: bytes, timeout_seconds: int) -> bool
async
Writes to a nonblocking file descriptor with the timeout.
Returns True if all the data was written. False indicates that there was either a timeout or a broken pipe.
This function does not close the file descriptor.
Source code in src/bounded_subprocess/util.py
write_nonblocking_sync(*, fd, data: bytes, timeout_seconds: int) -> bool
Writes to a nonblocking file descriptor with the timeout.
Returns True if all the data was written. False indicates that there was either a timeout or a broken pipe.
This function does not close the file descriptor.