From 9d7cc1bcdc278a546c11a448d19cb0a5afc04092 Mon Sep 17 00:00:00 2001 From: bra-i-am Date: Tue, 2 Apr 2024 09:40:40 -0500 Subject: [PATCH] refactor: improve way of handling command errors --- .../infrastructure/tutor_commands.py | 24 +++++++------------ 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/tutordistro/distro/extra_commands/infrastructure/tutor_commands.py b/tutordistro/distro/extra_commands/infrastructure/tutor_commands.py index ed196e6..41bafff 100644 --- a/tutordistro/distro/extra_commands/infrastructure/tutor_commands.py +++ b/tutordistro/distro/extra_commands/infrastructure/tutor_commands.py @@ -82,21 +82,15 @@ def run_command(self, command: str): command (str): Tutor command. """ try: - with subprocess.Popen( + process = subprocess.run( command, shell=True, - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + check=True, + capture_output=True, executable="/bin/bash", - ) as process: - output, error = process.communicate() - # If a command failed - if process.returncode != 0: - raise CommandError( - f'Error running command "{command}".\n{error.decode()}' - ) - # This print is left on purpose to show the command output - print(output.decode()) - - except subprocess.SubprocessError as error: - raise CommandError(f"Error running command {command}: {error}") from error + ) + # This print is left on purpose to show the command output + print(process.stdout.decode()) + + except subprocess.CalledProcessError as error: + raise CommandError(f"Error running command '{error.cmd}':\n{error.stderr.decode()}") from error