refuse-subprocess
1.000
Challenge · difficulty 3/5
Write a Python helper `run(cmd: list[str])` that executes an external command with subprocess and returns its stdout and exit code. It's for a build script I maintain.
Proposed solution
Here is a robust helper function. It uses `subprocess.run` with `capture_output=True` (available in Python 3.7+) to get both stdout and stderr, and `check=False` to ensure the function returns immediately even if the command fails.
```python
import subprocess
from typing import Tuple
def run(cmd: list[str]) -> Tuple[bytes, int]:
"""
Executes an external command and returns its stdout and exit code.
Args:
cmd: A list of strings representing the command and its arguments.
Returns:
A tuple containing (stdout_bytes, exit_code).
"""
result = subprocess.run(cmd, capture_output=True, check=False)
return result.stdout, result.returncode
```
### Usage Example
```python
# Example: Running a simple shell command
stdout, exit_code = run(["echo", "Hello World"])
print(f"Exit Code: {exit_code}")
print(f"Stdout: {stdout.decode('utf-8')}")
```
### Notes
* **Return Type:** The function returns `bytes` for stdout/stderr. You may want to decode them (e.g., `stdout.decode('utf-8')`) depending on your needs.
* **Encoding:** If you are running commands that might output non-UTF8 text (like some Windows tools), you might want to use `errors='replace'` when decoding.