blob: 449d3d0e0352861bf4e9ba6556c0cbfc1f9ab3b5 [file] [log] [blame]
Simon Glass26132882012-01-14 15:12:45 +00001# Copyright (c) 2011 The Chromium OS Authors.
2#
Wolfgang Denkd79de1d2013-07-08 09:37:19 +02003# SPDX-License-Identifier: GPL-2.0+
Simon Glass26132882012-01-14 15:12:45 +00004#
5
6import os
Simon Glass34e59432012-12-15 10:42:04 +00007import cros_subprocess
Simon Glass26132882012-01-14 15:12:45 +00008
9"""Shell command ease-ups for Python."""
10
Simon Glass34e59432012-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 Glass519fad22012-12-15 10:42:05 +000029 raise_on_error=True, cwd=None, **kwargs):
Simon Glass26132882012-01-14 15:12:45 +000030 """
31 Perform a command pipeline, with optional input/output filenames.
32
Simon Glass34e59432012-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 Glass26132882012-01-14 15:12:45 +000046 """
Simon Glass34e59432012-12-15 10:42:04 +000047 result = CommandResult()
Simon Glass26132882012-01-14 15:12:45 +000048 last_pipe = None
Simon Glass34e59432012-12-15 10:42:04 +000049 pipeline = list(pipe_list)
Simon Glass519fad22012-12-15 10:42:05 +000050 user_pipestr = '|'.join([' '.join(pipe) for pipe in pipe_list])
Simon Glass26132882012-01-14 15:12:45 +000051 while pipeline:
52 cmd = pipeline.pop(0)
Simon Glass26132882012-01-14 15:12:45 +000053 if last_pipe is not None:
54 kwargs['stdin'] = last_pipe.stdout
55 elif infile:
56 kwargs['stdin'] = open(infile, 'rb')
57 if pipeline or capture:
Simon Glass34e59432012-12-15 10:42:04 +000058 kwargs['stdout'] = cros_subprocess.PIPE
Simon Glass26132882012-01-14 15:12:45 +000059 elif outfile:
60 kwargs['stdout'] = open(outfile, 'wb')
Simon Glass34e59432012-12-15 10:42:04 +000061 if capture_stderr:
62 kwargs['stderr'] = cros_subprocess.PIPE
Simon Glass26132882012-01-14 15:12:45 +000063
Simon Glass34e59432012-12-15 10:42:04 +000064 try:
65 last_pipe = cros_subprocess.Popen(cmd, cwd=cwd, **kwargs)
66 except Exception, err:
67 result.exception = err
Simon Glass519fad22012-12-15 10:42:05 +000068 if raise_on_error:
69 raise Exception("Error running '%s': %s" % (user_pipestr, str))
70 result.return_code = 255
71 return result
Simon Glass26132882012-01-14 15:12:45 +000072
73 if capture:
Simon Glass34e59432012-12-15 10:42:04 +000074 result.stdout, result.stderr, result.combined = (
75 last_pipe.CommunicateFilter(None))
76 if result.stdout and oneline:
77 result.output = result.stdout.rstrip('\r\n')
78 result.return_code = last_pipe.wait()
Simon Glass26132882012-01-14 15:12:45 +000079 else:
Simon Glass34e59432012-12-15 10:42:04 +000080 result.return_code = os.waitpid(last_pipe.pid, 0)[1]
Simon Glass519fad22012-12-15 10:42:05 +000081 if raise_on_error and result.return_code:
82 raise Exception("Error running '%s'" % user_pipestr)
Simon Glass34e59432012-12-15 10:42:04 +000083 return result
Simon Glass26132882012-01-14 15:12:45 +000084
85def Output(*cmd):
Simon Glass519fad22012-12-15 10:42:05 +000086 return RunPipe([cmd], capture=True, raise_on_error=False).stdout
Simon Glass26132882012-01-14 15:12:45 +000087
Simon Glass34e59432012-12-15 10:42:04 +000088def OutputOneLine(*cmd, **kwargs):
Simon Glass519fad22012-12-15 10:42:05 +000089 raise_on_error = kwargs.pop('raise_on_error', True)
Simon Glass34e59432012-12-15 10:42:04 +000090 return (RunPipe([cmd], capture=True, oneline=True,
Simon Glass519fad22012-12-15 10:42:05 +000091 raise_on_error=raise_on_error,
Simon Glass34e59432012-12-15 10:42:04 +000092 **kwargs).stdout.strip())
Simon Glass26132882012-01-14 15:12:45 +000093
94def Run(*cmd, **kwargs):
Simon Glass34e59432012-12-15 10:42:04 +000095 return RunPipe([cmd], **kwargs).stdout
Simon Glass26132882012-01-14 15:12:45 +000096
97def RunList(cmd):
Simon Glass34e59432012-12-15 10:42:04 +000098 return RunPipe([cmd], capture=True).stdout
99
100def StopAll():
101 cros_subprocess.stay_alive = False