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