blob: bebc495b5994e2bc7e5c3f7a856a24166581f42f [file] [log] [blame]
Simon Glass0d24de92012-01-14 15:12:45 +00001# Copyright (c) 2011 The Chromium OS Authors.
2#
Wolfgang Denk1a459662013-07-08 09:37:19 +02003# SPDX-License-Identifier: GPL-2.0+
Simon Glass0d24de92012-01-14 15:12:45 +00004#
5
6import os
Simon Glassa10fd932012-12-15 10:42:04 +00007import cros_subprocess
Simon Glass0d24de92012-01-14 15:12:45 +00008
9"""Shell command ease-ups for Python."""
10
Simon Glassa10fd932012-12-15 10:42:04 +000011class CommandResult:
12 """A class which captures the result of executing a command.
13
14 Members:
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
19 """
20 def __init__(self):
21 self.stdout = None
22 self.stderr = None
Simon Glass82012dd2014-09-05 19:00:12 -060023 self.combined = None
Simon Glassa10fd932012-12-15 10:42:04 +000024 self.return_code = None
25 self.exception = None
26
Simon Glass82012dd2014-09-05 19:00:12 -060027 def __init__(self, stdout='', stderr='', combined='', return_code=0,
28 exception=None):
29 self.stdout = stdout
30 self.stderr = stderr
31 self.combined = combined
32 self.return_code = return_code
33 self.exception = exception
34
35
36# This permits interception of RunPipe for test purposes. If it is set to
37# a function, then that function is called with the pipe list being
38# executed. Otherwise, it is assumed to be a CommandResult object, and is
39# returned as the result for every RunPipe() call.
40# When this value is None, commands are executed as normal.
41test_result = None
Simon Glassa10fd932012-12-15 10:42:04 +000042
43def RunPipe(pipe_list, infile=None, outfile=None,
44 capture=False, capture_stderr=False, oneline=False,
Simon Glassdc191502012-12-15 10:42:05 +000045 raise_on_error=True, cwd=None, **kwargs):
Simon Glass0d24de92012-01-14 15:12:45 +000046 """
47 Perform a command pipeline, with optional input/output filenames.
48
Simon Glassa10fd932012-12-15 10:42:04 +000049 Args:
50 pipe_list: List of command lines to execute. Each command line is
51 piped into the next, and is itself a list of strings. For
52 example [ ['ls', '.git'] ['wc'] ] will pipe the output of
53 'ls .git' into 'wc'.
54 infile: File to provide stdin to the pipeline
55 outfile: File to store stdout
56 capture: True to capture output
57 capture_stderr: True to capture stderr
58 oneline: True to strip newline chars from output
59 kwargs: Additional keyword arguments to cros_subprocess.Popen()
60 Returns:
61 CommandResult object
Simon Glass0d24de92012-01-14 15:12:45 +000062 """
Simon Glass82012dd2014-09-05 19:00:12 -060063 if test_result:
64 if hasattr(test_result, '__call__'):
65 return test_result(pipe_list=pipe_list)
66 return test_result
Simon Glassa10fd932012-12-15 10:42:04 +000067 result = CommandResult()
Simon Glass0d24de92012-01-14 15:12:45 +000068 last_pipe = None
Simon Glassa10fd932012-12-15 10:42:04 +000069 pipeline = list(pipe_list)
Simon Glassdc191502012-12-15 10:42:05 +000070 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
Simon Glassddaf5c82014-09-05 19:00:09 -060071 kwargs['stdout'] = None
72 kwargs['stderr'] = None
Simon Glass0d24de92012-01-14 15:12:45 +000073 while pipeline:
74 cmd = pipeline.pop(0)
Simon Glass0d24de92012-01-14 15:12:45 +000075 if last_pipe is not None:
76 kwargs['stdin'] = last_pipe.stdout
77 elif infile:
78 kwargs['stdin'] = open(infile, 'rb')
79 if pipeline or capture:
Simon Glassa10fd932012-12-15 10:42:04 +000080 kwargs['stdout'] = cros_subprocess.PIPE
Simon Glass0d24de92012-01-14 15:12:45 +000081 elif outfile:
82 kwargs['stdout'] = open(outfile, 'wb')
Simon Glassa10fd932012-12-15 10:42:04 +000083 if capture_stderr:
84 kwargs['stderr'] = cros_subprocess.PIPE
Simon Glass0d24de92012-01-14 15:12:45 +000085
Simon Glassa10fd932012-12-15 10:42:04 +000086 try:
87 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
Paul Burtonac3fde92016-09-27 16:03:51 +010088 except Exception as err:
Simon Glassa10fd932012-12-15 10:42:04 +000089 result.exception = err
Simon Glassdc191502012-12-15 10:42:05 +000090 if raise_on_error:
91 raise Exception("Error running '%s': %s" % (user_pipestr, str))
92 result.return_code = 255
93 return result
Simon Glass0d24de92012-01-14 15:12:45 +000094
95 if capture:
Simon Glassa10fd932012-12-15 10:42:04 +000096 result.stdout, result.stderr, result.combined = (
97 last_pipe.CommunicateFilter(None))
98 if result.stdout and oneline:
99 result.output = result.stdout.rstrip('\r\n')
100 result.return_code = last_pipe.wait()
Simon Glass0d24de92012-01-14 15:12:45 +0000101 else:
Simon Glassa10fd932012-12-15 10:42:04 +0000102 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
Simon Glassdc191502012-12-15 10:42:05 +0000103 if raise_on_error and result.return_code:
104 raise Exception("Error running '%s'" % user_pipestr)
Simon Glassa10fd932012-12-15 10:42:04 +0000105 return result
Simon Glass0d24de92012-01-14 15:12:45 +0000106
Simon Glass785f1542016-07-25 18:59:00 -0600107def Output(*cmd, **kwargs):
108 raise_on_error = kwargs.get('raise_on_error', True)
109 return RunPipe([cmd], capture=True, raise_on_error=raise_on_error).stdout
Simon Glass0d24de92012-01-14 15:12:45 +0000110
Simon Glassa10fd932012-12-15 10:42:04 +0000111def OutputOneLine(*cmd, **kwargs):
Simon Glassdc191502012-12-15 10:42:05 +0000112 raise_on_error = kwargs.pop('raise_on_error', True)
Simon Glassa10fd932012-12-15 10:42:04 +0000113 return (RunPipe([cmd], capture=True, oneline=True,
Simon Glassdc191502012-12-15 10:42:05 +0000114 raise_on_error=raise_on_error,
Simon Glassa10fd932012-12-15 10:42:04 +0000115 **kwargs).stdout.strip())
Simon Glass0d24de92012-01-14 15:12:45 +0000116
117def Run(*cmd, **kwargs):
Simon Glassa10fd932012-12-15 10:42:04 +0000118 return RunPipe([cmd], **kwargs).stdout
Simon Glass0d24de92012-01-14 15:12:45 +0000119
120def RunList(cmd):
Simon Glassa10fd932012-12-15 10:42:04 +0000121 return RunPipe([cmd], capture=True).stdout
122
123def StopAll():
124 cros_subprocess.stay_alive = False