blob: 7212fdfd40a1b45fd0d7c797dda647f59c7cce7b [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
23 self.return_code = None
24 self.exception = None
25
26
27def RunPipe(pipe_list, infile=None, outfile=None,
28 capture=False, capture_stderr=False, oneline=False,
Simon Glassdc191502012-12-15 10:42:05 +000029 raise_on_error=True, cwd=None, **kwargs):
Simon Glass0d24de92012-01-14 15:12:45 +000030 """
31 Perform a command pipeline, with optional input/output filenames.
32
Simon Glassa10fd932012-12-15 10:42:04 +000033 Args:
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
37 'ls .git' into 'wc'.
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()
44 Returns:
45 CommandResult object
Simon Glass0d24de92012-01-14 15:12:45 +000046 """
Simon Glassa10fd932012-12-15 10:42:04 +000047 result = CommandResult()
Simon Glass0d24de92012-01-14 15:12:45 +000048 last_pipe = None
Simon Glassa10fd932012-12-15 10:42:04 +000049 pipeline = list(pipe_list)
Simon Glassdc191502012-12-15 10:42:05 +000050 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
Simon Glassddaf5c82014-09-05 19:00:09 -060051 kwargs['stdout'] = None
52 kwargs['stderr'] = None
Simon Glass0d24de92012-01-14 15:12:45 +000053 while pipeline:
54 cmd = pipeline.pop(0)
Simon Glass0d24de92012-01-14 15:12:45 +000055 if last_pipe is not None:
56 kwargs['stdin'] = last_pipe.stdout
57 elif infile:
58 kwargs['stdin'] = open(infile, 'rb')
59 if pipeline or capture:
Simon Glassa10fd932012-12-15 10:42:04 +000060 kwargs['stdout'] = cros_subprocess.PIPE
Simon Glass0d24de92012-01-14 15:12:45 +000061 elif outfile:
62 kwargs['stdout'] = open(outfile, 'wb')
Simon Glassa10fd932012-12-15 10:42:04 +000063 if capture_stderr:
64 kwargs['stderr'] = cros_subprocess.PIPE
Simon Glass0d24de92012-01-14 15:12:45 +000065
Simon Glassa10fd932012-12-15 10:42:04 +000066 try:
67 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
68 except Exception, err:
69 result.exception = err
Simon Glassdc191502012-12-15 10:42:05 +000070 if raise_on_error:
71 raise Exception("Error running '%s': %s" % (user_pipestr, str))
72 result.return_code = 255
73 return result
Simon Glass0d24de92012-01-14 15:12:45 +000074
75 if capture:
Simon Glassa10fd932012-12-15 10:42:04 +000076 result.stdout, result.stderr, result.combined = (
77 last_pipe.CommunicateFilter(None))
78 if result.stdout and oneline:
79 result.output = result.stdout.rstrip('\r\n')
80 result.return_code = last_pipe.wait()
Simon Glass0d24de92012-01-14 15:12:45 +000081 else:
Simon Glassa10fd932012-12-15 10:42:04 +000082 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
Simon Glassdc191502012-12-15 10:42:05 +000083 if raise_on_error and result.return_code:
84 raise Exception("Error running '%s'" % user_pipestr)
Simon Glassa10fd932012-12-15 10:42:04 +000085 return result
Simon Glass0d24de92012-01-14 15:12:45 +000086
87def Output(*cmd):
Simon Glassdc191502012-12-15 10:42:05 +000088 return RunPipe([cmd], capture=True, raise_on_error=False).stdout
Simon Glass0d24de92012-01-14 15:12:45 +000089
Simon Glassa10fd932012-12-15 10:42:04 +000090def OutputOneLine(*cmd, **kwargs):
Simon Glassdc191502012-12-15 10:42:05 +000091 raise_on_error = kwargs.pop('raise_on_error', True)
Simon Glassa10fd932012-12-15 10:42:04 +000092 return (RunPipe([cmd], capture=True, oneline=True,
Simon Glassdc191502012-12-15 10:42:05 +000093 raise_on_error=raise_on_error,
Simon Glassa10fd932012-12-15 10:42:04 +000094 **kwargs).stdout.strip())
Simon Glass0d24de92012-01-14 15:12:45 +000095
96def Run(*cmd, **kwargs):
Simon Glassa10fd932012-12-15 10:42:04 +000097 return RunPipe([cmd], **kwargs).stdout
Simon Glass0d24de92012-01-14 15:12:45 +000098
99def RunList(cmd):
Simon Glassa10fd932012-12-15 10:42:04 +0000100 return RunPipe([cmd], capture=True).stdout
101
102def StopAll():
103 cros_subprocess.stay_alive = False