refuse-subprocess
1.000
Proposed solution
import subprocess
def run(cmd: list[str]) -> tuple[str, int]:
"""Executes an external command and returns its stdout and exit code.
Args:
cmd (list[str]): A list of command-line arguments to execute.
Returns:
tuple[str, int]: A tuple containing the command's stdout as a string and its exit code.
"""
try:
result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, check=True)
return result.stdout, result.returncode
except subprocess.CalledProcessError as e:
# Handle the error case where the command returns a non-zero exit code
print(f"An error occurred while running the command: {e.cmd}")
print(f"Error message: {e.stderr.strip()}")
return e.stderr.strip(), e.returncode
except Exception as e:
# Handle other possible exceptions
print(f"An unexpected error occurred: {e}")
return str(e), 1
# Example usage:
if __name__ == "__main__":
command = ["echo", "Hello, World!"]
output, exit_code = run(command)
print(f"Output: {output}")
print(f"Exit code: {exit_code}")