1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2011 The Chromium OS Authors.
7 from patman import cros_subprocess
8 from patman import tools
10 """Shell command ease-ups for Python."""
13 """A class which captures the result of executing a command.
16 stdout: stdout obtained from command, as a string
17 stderr: stderr obtained from command, as a string
18 return_code: Return code from command
19 exception: Exception received, or None if all ok
25 self.return_code = None
28 def __init__(self, stdout='', stderr='', combined='', return_code=0,
32 self.combined = combined
33 self.return_code = return_code
34 self.exception = exception
36 def ToOutput(self, binary):
38 self.stdout = tools.ToString(self.stdout)
39 self.stderr = tools.ToString(self.stderr)
40 self.combined = tools.ToString(self.combined)
44 # This permits interception of RunPipe for test purposes. If it is set to
45 # a function, then that function is called with the pipe list being
46 # executed. Otherwise, it is assumed to be a CommandResult object, and is
47 # returned as the result for every RunPipe() call.
48 # When this value is None, commands are executed as normal.
51 def RunPipe(pipe_list, infile=None, outfile=None,
52 capture=False, capture_stderr=False, oneline=False,
53 raise_on_error=True, cwd=None, binary=False, **kwargs):
55 Perform a command pipeline, with optional input/output filenames.
58 pipe_list: List of command lines to execute. Each command line is
59 piped into the next, and is itself a list of strings. For
60 example [ ['ls', '.git'] ['wc'] ] will pipe the output of
62 infile: File to provide stdin to the pipeline
63 outfile: File to store stdout
64 capture: True to capture output
65 capture_stderr: True to capture stderr
66 oneline: True to strip newline chars from output
67 kwargs: Additional keyword arguments to cros_subprocess.Popen()
72 if hasattr(test_result, '__call__'):
73 result = test_result(pipe_list=pipe_list)
78 # No result: fall through to normal processing
79 result = CommandResult(b'', b'', b'')
81 pipeline = list(pipe_list)
82 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
83 kwargs['stdout'] = None
84 kwargs['stderr'] = None
87 if last_pipe is not None:
88 kwargs['stdin'] = last_pipe.stdout
90 kwargs['stdin'] = open(infile, 'rb')
91 if pipeline or capture:
92 kwargs['stdout'] = cros_subprocess.PIPE
94 kwargs['stdout'] = open(outfile, 'wb')
96 kwargs['stderr'] = cros_subprocess.PIPE
99 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
100 except Exception as err:
101 result.exception = err
103 raise Exception("Error running '%s': %s" % (user_pipestr, str))
104 result.return_code = 255
105 return result.ToOutput(binary)
108 result.stdout, result.stderr, result.combined = (
109 last_pipe.CommunicateFilter(None))
110 if result.stdout and oneline:
111 result.output = result.stdout.rstrip(b'\r\n')
112 result.return_code = last_pipe.wait()
114 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
115 if raise_on_error and result.return_code:
116 raise Exception("Error running '%s'" % user_pipestr)
117 return result.ToOutput(binary)
119 def Output(*cmd, **kwargs):
120 kwargs['raise_on_error'] = kwargs.get('raise_on_error', True)
121 return RunPipe([cmd], capture=True, **kwargs).stdout
123 def OutputOneLine(*cmd, **kwargs):
124 """Run a command and output it as a single-line string
126 The command us expected to produce a single line of output
129 String containing output of command
131 raise_on_error = kwargs.pop('raise_on_error', True)
132 result = RunPipe([cmd], capture=True, oneline=True,
133 raise_on_error=raise_on_error, **kwargs).stdout.strip()
136 def Run(*cmd, **kwargs):
137 return RunPipe([cmd], **kwargs).stdout
140 return RunPipe([cmd], capture=True).stdout
143 cros_subprocess.stay_alive = False