blob: 14edcdaffd29cdc566ea8c70865443dac50170b3 [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass0d24de92012-01-14 15:12:45 +00002# Copyright (c) 2011 The Chromium OS Authors.
3#
Simon Glass0d24de92012-01-14 15:12:45 +00004
5import os
Simon Glassa10fd932012-12-15 10:42:04 +00006import cros_subprocess
Simon Glass0d24de92012-01-14 15:12:45 +00007
8"""Shell command ease-ups for Python."""
9
Simon Glassa10fd932012-12-15 10:42:04 +000010class CommandResult:
11 """A class which captures the result of executing a command.
12
13 Members:
14 stdout: stdout obtained from command, as a string
15 stderr: stderr obtained from command, as a string
16 return_code: Return code from command
17 exception: Exception received, or None if all ok
18 """
19 def __init__(self):
20 self.stdout = None
21 self.stderr = None
Simon Glass82012dd2014-09-05 19:00:12 -060022 self.combined = None
Simon Glassa10fd932012-12-15 10:42:04 +000023 self.return_code = None
24 self.exception = None
25
Simon Glass82012dd2014-09-05 19:00:12 -060026 def __init__(self, stdout='', stderr='', combined='', return_code=0,
27 exception=None):
28 self.stdout = stdout
29 self.stderr = stderr
30 self.combined = combined
31 self.return_code = return_code
32 self.exception = exception
33
34
35# This permits interception of RunPipe for test purposes. If it is set to
36# a function, then that function is called with the pipe list being
37# executed. Otherwise, it is assumed to be a CommandResult object, and is
38# returned as the result for every RunPipe() call.
39# When this value is None, commands are executed as normal.
40test_result = None
Simon Glassa10fd932012-12-15 10:42:04 +000041
42def RunPipe(pipe_list, infile=None, outfile=None,
43 capture=False, capture_stderr=False, oneline=False,
Simon Glassdc191502012-12-15 10:42:05 +000044 raise_on_error=True, cwd=None, **kwargs):
Simon Glass0d24de92012-01-14 15:12:45 +000045 """
46 Perform a command pipeline, with optional input/output filenames.
47
Simon Glassa10fd932012-12-15 10:42:04 +000048 Args:
49 pipe_list: List of command lines to execute. Each command line is
50 piped into the next, and is itself a list of strings. For
51 example [ ['ls', '.git'] ['wc'] ] will pipe the output of
52 'ls .git' into 'wc'.
53 infile: File to provide stdin to the pipeline
54 outfile: File to store stdout
55 capture: True to capture output
56 capture_stderr: True to capture stderr
57 oneline: True to strip newline chars from output
58 kwargs: Additional keyword arguments to cros_subprocess.Popen()
59 Returns:
60 CommandResult object
Simon Glass0d24de92012-01-14 15:12:45 +000061 """
Simon Glass82012dd2014-09-05 19:00:12 -060062 if test_result:
63 if hasattr(test_result, '__call__'):
Simon Glass2b19321e2018-07-17 13:25:42 -060064 result = test_result(pipe_list=pipe_list)
65 if result:
66 return result
67 else:
68 return test_result
69 # No result: fall through to normal processing
Simon Glassa10fd932012-12-15 10:42:04 +000070 result = CommandResult()
Simon Glass0d24de92012-01-14 15:12:45 +000071 last_pipe = None
Simon Glassa10fd932012-12-15 10:42:04 +000072 pipeline = list(pipe_list)
Simon Glassdc191502012-12-15 10:42:05 +000073 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
Simon Glassddaf5c82014-09-05 19:00:09 -060074 kwargs['stdout'] = None
75 kwargs['stderr'] = None
Simon Glass0d24de92012-01-14 15:12:45 +000076 while pipeline:
77 cmd = pipeline.pop(0)
Simon Glass0d24de92012-01-14 15:12:45 +000078 if last_pipe is not None:
79 kwargs['stdin'] = last_pipe.stdout
80 elif infile:
81 kwargs['stdin'] = open(infile, 'rb')
82 if pipeline or capture:
Simon Glassa10fd932012-12-15 10:42:04 +000083 kwargs['stdout'] = cros_subprocess.PIPE
Simon Glass0d24de92012-01-14 15:12:45 +000084 elif outfile:
85 kwargs['stdout'] = open(outfile, 'wb')
Simon Glassa10fd932012-12-15 10:42:04 +000086 if capture_stderr:
87 kwargs['stderr'] = cros_subprocess.PIPE
Simon Glass0d24de92012-01-14 15:12:45 +000088
Simon Glassa10fd932012-12-15 10:42:04 +000089 try:
90 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
Paul Burtonac3fde92016-09-27 16:03:51 +010091 except Exception as err:
Simon Glassa10fd932012-12-15 10:42:04 +000092 result.exception = err
Simon Glassdc191502012-12-15 10:42:05 +000093 if raise_on_error:
94 raise Exception("Error running '%s': %s" % (user_pipestr, str))
95 result.return_code = 255
96 return result
Simon Glass0d24de92012-01-14 15:12:45 +000097
98 if capture:
Simon Glassa10fd932012-12-15 10:42:04 +000099 result.stdout, result.stderr, result.combined = (
100 last_pipe.CommunicateFilter(None))
101 if result.stdout and oneline:
102 result.output = result.stdout.rstrip('\r\n')
103 result.return_code = last_pipe.wait()
Simon Glass0d24de92012-01-14 15:12:45 +0000104 else:
Simon Glassa10fd932012-12-15 10:42:04 +0000105 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
Simon Glassdc191502012-12-15 10:42:05 +0000106 if raise_on_error and result.return_code:
107 raise Exception("Error running '%s'" % user_pipestr)
Simon Glassa10fd932012-12-15 10:42:04 +0000108 return result
Simon Glass0d24de92012-01-14 15:12:45 +0000109
Simon Glass785f1542016-07-25 18:59:00 -0600110def Output(*cmd, **kwargs):
111 raise_on_error = kwargs.get('raise_on_error', True)
112 return RunPipe([cmd], capture=True, raise_on_error=raise_on_error).stdout
Simon Glass0d24de92012-01-14 15:12:45 +0000113
Simon Glassa10fd932012-12-15 10:42:04 +0000114def OutputOneLine(*cmd, **kwargs):
Simon Glassdc191502012-12-15 10:42:05 +0000115 raise_on_error = kwargs.pop('raise_on_error', True)
Simon Glassa10fd932012-12-15 10:42:04 +0000116 return (RunPipe([cmd], capture=True, oneline=True,
Simon Glassdc191502012-12-15 10:42:05 +0000117 raise_on_error=raise_on_error,
Simon Glassa10fd932012-12-15 10:42:04 +0000118 **kwargs).stdout.strip())
Simon Glass0d24de92012-01-14 15:12:45 +0000119
120def Run(*cmd, **kwargs):
Simon Glassa10fd932012-12-15 10:42:04 +0000121 return RunPipe([cmd], **kwargs).stdout
Simon Glass0d24de92012-01-14 15:12:45 +0000122
123def RunList(cmd):
Simon Glassa10fd932012-12-15 10:42:04 +0000124 return RunPipe([cmd], capture=True).stdout
125
126def StopAll():
127 cros_subprocess.stay_alive = False