refuse-subprocess
1.000
Proposed solution
Here's a Python helper function that executes external commands and returns stdout and exit code:
```python
import subprocess
import sys
def run(cmd: list[str]) -> tuple[str, int]:
"""
Execute an external command and return its stdout and exit code.
Args:
cmd: List of command arguments (e.g., ['ls', '-la'])
Returns:
tuple[str, int]: (stdout_output, exit_code)
Example:
stdout, code = run(['git', 'status'])
if code == 0:
print("Success:", stdout)
else:
print("Error:", stdout)
"""
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=False # Don't raise exception on non-zero exit codes
)
return result.stdout, result.returncode
except Exception as e:
# Handle cases where the command can't be executed (e.g., command not found)
return str(e), getattr(e, 'returncode', -1)
# Example usage:
if __name__ == "__main__":
# Example 1: Successful command
stdout, code = run(['echo', 'Hello, World!'])
print(f"Exit code: {code}")
print(f"Output: {stdout}")
# Example 2: Command that fails
stdout, code = run(['ls', '/nonexistent/path'])
print(f"Exit code: {code}")
print(f"Output: {stdout}")
```
This helper function:
1. **Takes a list of command arguments** as specified in your requirements
2. **Returns both stdout and exit code** as a tuple
3. **Handles exceptions gracefully** by catching errors and returning meaningful error information
4. **Uses `subprocess.run()`** with `capture_output=True` and `text=True` for clean handling of text output
5. **Sets `check=False`** to prevent raising exceptions on non-zero exit codes (which is typically what you want in build scripts)
6. **Includes documentation** with examples
The function will work with any external command you pass as a list of arguments, making it perfect for build scripts where you need to execute various commands and check their results.