A Python port of the Invisible Internet Project (I2P)
1"""Shell command execution with timeout.
2
3Ported from net.i2p.util.ShellCommand.
4"""
5
6from __future__ import annotations
7
8import subprocess
9
10
11def shell_command(
12 cmd: str, timeout: float | None = None
13) -> tuple[int, str, str]:
14 """Execute a shell command.
15
16 Returns (return_code, stdout, stderr).
17 On timeout, returns (-1, '', 'timeout').
18 """
19 try:
20 result = subprocess.run(
21 cmd,
22 shell=True, # nosec B602 — ported from Java ShellCommand; callers pass trusted commands
23 capture_output=True,
24 text=True,
25 timeout=timeout,
26 )
27 return result.returncode, result.stdout, result.stderr
28 except subprocess.TimeoutExpired:
29 return -1, "", "timeout"
30 except OSError as e:
31 return -1, "", str(e)