From: Michael Tremer Date: Sat, 8 May 2021 12:42:07 +0000 (+0000) Subject: command: Add function to call shell commands X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=4fcf8427be1e878e391eeaf9424f67d1ad877f6f;p=people%2Fms%2Fbricklayer.git command: Add function to call shell commands These commands will be executed and an error might be shown if something went wrong. Signed-off-by: Michael Tremer --- diff --git a/src/python/__init__.py b/src/python/__init__.py index 724aca3..4c09d38 100644 --- a/src/python/__init__.py +++ b/src/python/__init__.py @@ -19,6 +19,7 @@ ############################################################################### import logging +import subprocess import sys import traceback @@ -95,6 +96,29 @@ class Bricklayer(object): except InstallAbortedError: return 1 + # Catch any failed commands + except subprocess.CalledProcessError as e: + args = { + "command" : " ".join(e.cmd), + "output" : e.output.decode(), + "returncode" : e.returncode, + } + + # Log the error + log.error("Command \"%(command)s\" failed with error code " + "%(returncode)s:\n%(output)s" % args) + + # Format the error message + error = _("Command \"%(command)s\" failed with error code " + "%(returncode)s:\n\n%(output)s" % args) + + # Show it + self.tui.error(_("An Unexpected Error Occured"), error, + buttons=[_("Exit")], width=78) + + # Exit + return e.returncode + # Catch all other exceptions and show an error except: type, value, tb = sys.exc_info() @@ -133,3 +157,24 @@ class Bricklayer(object): """ with open("/etc/os-release") as f: return util.config_read(f) + + def command(self, command): + """ + Runs a command in a shell environment + """ + log.debug("Running command: %s" % " ".join(command)) + + # Execute the command + p = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + + # Check the return code (raises CalledProcessError on non-zero) + p.check_returncode() + + # Decode output + output = p.stdout.decode() + + # Log output + if output: + log.debug(output) + + return output