def printConfirm(msg, assumeYes=False): if assumeYes: return OK(True) logger.info(msg) try: res = input('Proceed? [N/y] ') if res.lower().startswith('y'): logger.info('... proceeding') return OK(True) return Fail(UserInterruptError(message="User interrupted.")) except KeyboardInterrupt as err: return Fail(UserInterruptError(message="User interrupted."))
def procCommand(cmd, cwd=None, shell=False): try: logger.debug("COMMAND: %s", cmd) proc = Popen(shlex.split(cmd), shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) pout, perr = proc.communicate() pout = pout.decode() perr = perr.decode() if proc.returncode == 0: return OK({ "code": proc.returncode, "stdout": pout, "stderr": perr }) else: return Fail( ShellCommandError(code=proc.returncode, message=pout, stdout=pout, stderr=perr)) except KeyboardInterrupt: logger.info("CTRL-C Received...Exiting.") return Fail(UserInterruptError(message="User interrupted."))
def streamCommand(cmd, cwd=None, shell=False, stream=False): try: logger.debug("COMMAND: %s", cmd) proc = Popen(shlex.split(cmd), shell=shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd) stdout = '' stderr = '' while True: d = proc.stdout.read(1) if d != '': stdout += d if stream: sys.stdout.write(d) sys.stdout.flush() de = proc.stderr.read(1) if de != '': stderr += de if stream: sys.stderr.write(de) sys.stderr.flush() if d == '' and de == '' and proc.poll() is not None: break if proc.returncode == 0: return OK({"code": proc.returncode, "stdout": stdout, "stderr": stderr}) else: return Fail(ShellCommandError(code=proc.returncode, message=stdout, stdout=stdout, stderr=stderr)) except OSError as err: err.strerror = "Error running '%s': %s" % (cmd, err.strerror) return Fail(err) except KeyboardInterrupt: logger.info("CTRL-C Received...Exiting.") return Fail(UserInterruptError(message="User interrupted."))
def call(cmd, cwd=None, shell=True): logger.debug("COMMAND[%s]: %s", cwd, cmd) try: returncode = call(cmd, shell=shell, cwd=cwd) if returncode == 0: return OK(None) else: return Fail(ShellCommandError(code=returncode)) except CalledProcessError as err: return Fail(ShellCommandError(code=err.returncode, message=err.output, stdout=err.output)) except KeyboardInterrupt as err: logger.info("CTRL-C Received...Exiting.") return Fail(UserInterruptError(message="User interrupted."))