Max Rasskazov | 6733144 | 2015-06-04 21:56:54 +0300 | [diff] [blame] | 1 | #-*- coding: utf-8 -*- |
| 2 | |
| 3 | import subprocess |
| 4 | import utils |
| 5 | |
| 6 | |
| 7 | class Shell(object): |
| 8 | |
| 9 | def __init__(self, logger=None): |
| 10 | if logger is None: |
| 11 | self.logger = utils.logger.getChild('Shell') |
| 12 | else: |
| 13 | self.logger = logger.getChild('Shell') |
| 14 | |
| 15 | def shell(self, cmd, raise_error=True): |
| 16 | self.logger.debug(cmd) |
| 17 | process = subprocess.Popen(cmd, |
| 18 | stdin=subprocess.PIPE, |
| 19 | stdout=subprocess.PIPE, |
| 20 | stderr=subprocess.PIPE, |
| 21 | shell=True) |
| 22 | out, err = process.communicate() |
| 23 | self.logger.debug(out) |
| 24 | exitcode = process.returncode |
| 25 | if process.returncode != 0 and raise_error: |
| 26 | msg = '"{cmd}" failed. Exit code == {exitcode}'\ |
| 27 | '\n\nSTDOUT: \n{out}'\ |
| 28 | '\n\nSTDERR: \n{err}'\ |
| 29 | .format(**(locals())) |
| 30 | self.logger.error(msg) |
| 31 | raise RuntimeError(msg) |
| 32 | return exitcode, out, err |