import subprocess from subprocess import CalledProcessError, PIPE, STDOUT import sys class Shell(object): """An advanced shell, with the ability to do dry-run and log commands""" def __init__(self, logger = False, dry = False): """ `logger` The logger `dry` Whether or not to not run any commands, and just print""" self.logger = logger self.dry = dry def call(self, *args): if self.dry or self.logger: self.logger.info("$ " + ' '.join(args)) if self.dry: return proc = None if self.logger: if hasattr(self.logger, "verbose"): proc = subprocess.Popen(args, stdout=sys.stdout, stderr=sys.stderr) else: proc = subprocess.Popen(args, stdout=PIPE, stderr=STDOUT) else: proc = subprocess.Popen(args) stdout, _ = proc.communicate() if self.logger and stdout: self.logger.info(stdout) if proc.returncode: raise CalledProcessError(proc.returncode, args)