1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2011 The Chromium OS Authors.
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
24 self.return_code = None
27 def __init__(self, stdout='', stderr='', combined='', return_code=0,
31 self.combined = combined
32 self.return_code = return_code
33 self.exception = exception
35 def ToOutput(self, binary):
37 self.stdout = tools.ToString(self.stdout)
38 self.stderr = tools.ToString(self.stderr)
39 self.combined = tools.ToString(self.combined)
43 # This permits interception of RunPipe for test purposes. If it is set to
44 # a function, then that function is called with the pipe list being
45 # executed. Otherwise, it is assumed to be a CommandResult object, and is
46 # returned as the result for every RunPipe() call.
47 # When this value is None, commands are executed as normal.
50 def RunPipe(pipe_list, infile=None, outfile=None,
51 capture=False, capture_stderr=False, oneline=False,
52 raise_on_error=True, cwd=None, binary=False, **kwargs):
54 Perform a command pipeline, with optional input/output filenames.
57 pipe_list: List of command lines to execute. Each command line is
58 piped into the next, and is itself a list of strings. For
59 example [ ['ls', '.git'] ['wc'] ] will pipe the output of
61 infile: File to provide stdin to the pipeline
62 outfile: File to store stdout
63 capture: True to capture output
64 capture_stderr: True to capture stderr
65 oneline: True to strip newline chars from output
66 kwargs: Additional keyword arguments to cros_subprocess.Popen()
71 if hasattr(test_result, '__call__'):
72 result = test_result(pipe_list=pipe_list)
77 # No result: fall through to normal processing
78 result = CommandResult(b'', b'', b'')
80 pipeline = list(pipe_list)
81 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
82 kwargs['stdout'] = None
83 kwargs['stderr'] = None
86 if last_pipe is not None:
87 kwargs['stdin'] = last_pipe.stdout
89 kwargs['stdin'] = open(infile, 'rb')
90 if pipeline or capture:
91 kwargs['stdout'] = cros_subprocess.PIPE
93 kwargs['stdout'] = open(outfile, 'wb')
95 kwargs['stderr'] = cros_subprocess.PIPE
98 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
99 except Exception as err:
100 result.exception = err
102 raise Exception("Error running '%s': %s" % (user_pipestr, str))
103 result.return_code = 255
104 return result.ToOutput(binary)
107 result.stdout, result.stderr, result.combined = (
108 last_pipe.CommunicateFilter(None))
109 if result.stdout and oneline:
110 result.output = result.stdout.rstrip(b'\r\n')
111 result.return_code = last_pipe.wait()
113 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
114 if raise_on_error and result.return_code:
115 raise Exception("Error running '%s'" % user_pipestr)
116 return result.ToOutput(binary)
118 def Output(*cmd, **kwargs):
119 kwargs['raise_on_error'] = kwargs.get('raise_on_error', True)
120 return RunPipe([cmd], capture=True, **kwargs).stdout
122 def OutputOneLine(*cmd, **kwargs):
123 """Run a command and output it as a single-line string
125 The command us expected to produce a single line of output
128 String containing output of command
130 raise_on_error = kwargs.pop('raise_on_error', True)
131 result = RunPipe([cmd], capture=True, oneline=True,
132 raise_on_error=raise_on_error, **kwargs).stdout.strip()
135 def Run(*cmd, **kwargs):
136 return RunPipe([cmd], **kwargs).stdout
139 return RunPipe([cmd], capture=True).stdout
142 cros_subprocess.stay_alive = False