From fcebcac5682c9768b878a47dfd996b9c53822105 Mon Sep 17 00:00:00 2001 From: Olivier Gayot Date: Mon, 21 Nov 2022 14:49:00 +0100 Subject: [PATCH] utils: inc. captured stdout / stderr when forging CalledProcessError When executing a command via arun_command with check=True, we forge and then raise a CalledProcessError exception if the command exits abnormally (i.e., exit code != 0). When doing so, we only instantiate the exception with the exit code and the command executed. This means that we lose access to any output captured so far. This is usually fine for stdout but stderr oftentimes contains invaluable information to understand what caused the command to exit abnormally. Back in Python 3.5, stdout and stderr were introduced as new attributes for CalledProcessError. We now also include stdout and stderr in the CalledProcessError instances that we forge. This allows us to access stderr (if any) when catching the exception with: try: ... except CalledProcessError as exc: print(exc.stderr) Signed-off-by: Olivier Gayot --- subiquitycore/utils.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/subiquitycore/utils.py b/subiquitycore/utils.py index 9535d652..72d487c7 100644 --- a/subiquitycore/utils.py +++ b/subiquitycore/utils.py @@ -102,7 +102,8 @@ async def arun_command(cmd: Sequence[str], *, # .communicate() forces returncode to be set to a value assert(proc.returncode is not None) if check and proc.returncode != 0: - raise subprocess.CalledProcessError(proc.returncode, cmd) + raise subprocess.CalledProcessError(proc.returncode, cmd, + stdout, stderr) else: return subprocess.CompletedProcess( cmd, proc.returncode, stdout, stderr)