File: utils.py

package info (click to toggle)
python-schroot 0.4-5
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 108 kB
  • sloc: python: 190; makefile: 3
file content (30 lines) | stat: -rw-r--r-- 984 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import subprocess
import shlex


def run_command(command, stdin=None, encoding='utf-8', return_codes=None,
                **kwargs):
    if not isinstance(command, list):
        command = shlex.split(command)
    try:
        pipe = subprocess.Popen(command, shell=False,
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                **kwargs)
    except OSError:
        return (None, None, -1)

    kwargs = {}
    if stdin:
        kwargs['input'] = stdin.read()

    (output, stderr) = (x.decode(encoding) for x in pipe.communicate(**kwargs))

    if return_codes is not None:
        if not isinstance(return_codes, tuple):
            return_codes = (return_codes, )
        if pipe.returncode not in return_codes:
            raise SchrootCommandError("Bad return code %d" % pipe.returncode)

    return (output, stderr, pipe.returncode)