1import subprocess
2
3
4class Command():
5    def __init__(self, command, inputstr):
6        self.command = command
7        self.inputstr = inputstr
8
9    def run(self, timeout=None):
10        """ Run a command then return: (status, output, error). """
11        status = None
12        output = ""
13        error = ""
14        try:
15            process = subprocess.Popen(self.command,
16                                       universal_newlines=True,
17                                       stdin=subprocess.PIPE,
18                                       stdout=subprocess.PIPE,
19                                       stderr=subprocess.PIPE)
20        except OSError:
21            return status, output, error
22        except ValueError:
23            return status, output, error
24
25        try:
26            output, error = process.communicate(
27                input=self.inputstr,
28                timeout=timeout)
29        except subprocess.TimeoutExpired:
30            process.kill()
31            output, error = process.communicate()
32
33        status = process.returncode
34        return status, output, error
35