diff --git a/src/cmd.py b/src/cmd.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b3d85e0cb09d1921a6e66c13c5740fbfce403d --- /dev/null +++ b/src/cmd.py @@ -0,0 +1,87 @@ +# Copyright 2018-2019 Florian Fischer <florian.fl.fischer@fau.de> +# +# This file is part of allocbench. +# +# allocbench is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# allocbench is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with allocbench. If not, see <http://www.gnu.org/licenses/>. +"""Callable wrapper classes for subprocess.run""" + +import subprocess + +import src.globalvars + + +class Cmd: + """subprocess.run wrapper which cares about verbosity""" + def __init__(self, + cmd, + output_verbosity=2, + capture=False, + shell=False, + check=True, + cwd=None, + input=None): + + if isinstance(cmd, str): + cmd = cmd.split() + self.cmd = cmd + + self.output_verbosity = output_verbosity + self.capture = capture + self.shell = shell + self.check = check + self.cwd = cwd + self.inpt = input + + def __run(self, inpt, cwd): + """execute the cmd in cwd and pass input to it""" + if self.capture: + stdout = subprocess.PIPE + stderr = stdout + elif src.globalvars.verbosity < self.output_verbosity: + stdout = subprocess.DEVNULL + stderr = stdout + else: + stdout = None + stderr = stdout + + return subprocess.run(self.cmd, + stdout=stdout, + stderr=stderr, + shell=self.shell, + check=self.check, + input=inpt, + cwd=cwd, + universal_newlines=True) + + def __call__(self): + """default execution with the arguments passed with __init__""" + return self.__run(self.inpt, self.cwd) + + def run_in_dir(self, cwd): + """execute cmd in a specific directory""" + return self.__run(self.inpt, cwd) + + +class ShellCmd(Cmd): + """A shell cmd and printing its output acording to our verbosity level""" + def __init__(self, + cmd, + output_verbosity=2, + capture=False, + check=True, + cwd=None, + input=None): + + super().__init__(cmd, output_verbosity, capture, True, check, cwd, + input)