2 from __future__ import absolute_import, print_function
3 from collections import namedtuple
4 from os.path import abspath, basename, dirname, realpath
5 from pipes import quote
6 from subprocess import PIPE, Popen
7 from traceback import extract_stack
8 import errno, os, subprocess, sys, tempfile
10 from bup import helpers
11 from bup.compat import fsencode
12 from bup.io import byte_stream
15 ex_res = namedtuple('SubprocResult', ['out', 'err', 'proc', 'rc'])
17 def run(cmd, check=True, input=None, **kwargs):
18 """Run a subprocess as per subprocess.Popen(cmd, **kwargs) followed by
19 communicate(input=input). If check is true, then throw an
20 exception if the subprocess exits with non-zero status. Return a
25 assert 'stdin' not in kwargs
26 kwargs['stdin'] = PIPE
27 p = Popen(cmd, **kwargs)
28 out, err = p.communicate(input=input)
29 if check and p.returncode != 0:
30 raise Exception('subprocess %r failed with status %d%s'
32 (', stderr: %r' % err) if err else ''))
33 return ex_res(out=out, err=err, proc=p, rc=p.returncode)
36 s = helpers.shstr(cmd)
37 if isinstance(cmd, str):
38 print(s, file=sys.stderr)
40 # bytes - for now just escape it
41 print(s.decode(errors='backslashreplace'), file=sys.stderr)
43 def ex(cmd, **kwargs):
44 """Print cmd to stderr and then run it as per ex(...).
45 Print the subprocess stderr to stderr if stderr=PIPE and there's
49 result = run(cmd, **kwargs)
52 byte_stream(sys.stderr).write(result.err)
55 def exo(cmd, **kwargs):
56 """Print cmd to stderr and then run it as per ex(..., stdout=PIPE).
57 Print the subprocess stderr to stderr if stderr=PIPE and there's
61 assert 'stdout' not in kwargs
62 kwargs['stdout'] = PIPE
63 return ex(cmd, **kwargs)