1 # Copyright (c) 2011 The Chromium OS Authors.
3 # SPDX-License-Identifier: GPL-2.0+
9 """Shell command ease-ups for Python."""
12 """A class which captures the result of executing a command.
15 stdout: stdout obtained from command, as a string
16 stderr: stderr obtained from command, as a string
17 return_code: Return code from command
18 exception: Exception received, or None if all ok
23 self.return_code = None
27 def RunPipe(pipe_list, infile=None, outfile=None,
28 capture=False, capture_stderr=False, oneline=False,
29 raise_on_error=True, cwd=None, **kwargs):
31 Perform a command pipeline, with optional input/output filenames.
34 pipe_list: List of command lines to execute. Each command line is
35 piped into the next, and is itself a list of strings. For
36 example [ ['ls', '.git'] ['wc'] ] will pipe the output of
38 infile: File to provide stdin to the pipeline
39 outfile: File to store stdout
40 capture: True to capture output
41 capture_stderr: True to capture stderr
42 oneline: True to strip newline chars from output
43 kwargs: Additional keyword arguments to cros_subprocess.Popen()
47 result = CommandResult()
49 pipeline = list(pipe_list)
50 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
53 if last_pipe is not None:
54 kwargs['stdin'] = last_pipe.stdout
56 kwargs['stdin'] = open(infile, 'rb')
57 if pipeline or capture:
58 kwargs['stdout'] = cros_subprocess.PIPE
60 kwargs['stdout'] = open(outfile, 'wb')
62 kwargs['stderr'] = cros_subprocess.PIPE
65 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
66 except Exception, err:
67 result.exception = err
69 raise Exception("Error running '%s': %s" % (user_pipestr, str))
70 result.return_code = 255
74 result.stdout, result.stderr, result.combined = (
75 last_pipe.CommunicateFilter(None))
76 if result.stdout and oneline:
77 result.output = result.stdout.rstrip('\r\n')
78 result.return_code = last_pipe.wait()
80 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
81 if raise_on_error and result.return_code:
82 raise Exception("Error running '%s'" % user_pipestr)
86 return RunPipe([cmd], capture=True, raise_on_error=False).stdout
88 def OutputOneLine(*cmd, **kwargs):
89 raise_on_error = kwargs.pop('raise_on_error', True)
90 return (RunPipe([cmd], capture=True, oneline=True,
91 raise_on_error=raise_on_error,
92 **kwargs).stdout.strip())
94 def Run(*cmd, **kwargs):
95 return RunPipe([cmd], **kwargs).stdout
98 return RunPipe([cmd], capture=True).stdout
101 cros_subprocess.stay_alive = False