blob: 4b00250c0297c64d4a39d3b51d7b57bee541fc94 [file] [log] [blame]
Simon Glass26132882012-01-14 15:12:45 +00001# Copyright (c) 2011 The Chromium OS Authors.
2#
3# See file CREDITS for list of people who contributed to this
4# project.
5#
6# This program is free software; you can redistribute it and/or
7# modify it under the terms of the GNU General Public License as
8# published by the Free Software Foundation; either version 2 of
9# the License, or (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program; if not, write to the Free Software
18# Foundation, Inc., 59 Temple Place, Suite 330, Boston,
19# MA 02111-1307 USA
20#
21
22import os
23import subprocess
24
25"""Shell command ease-ups for Python."""
26
27def RunPipe(pipeline, infile=None, outfile=None,
28 capture=False, oneline=False, hide_stderr=False):
29 """
30 Perform a command pipeline, with optional input/output filenames.
31
32 hide_stderr Don't allow output of stderr (default False)
33 """
34 last_pipe = None
35 while pipeline:
36 cmd = pipeline.pop(0)
37 kwargs = {}
38 if last_pipe is not None:
39 kwargs['stdin'] = last_pipe.stdout
40 elif infile:
41 kwargs['stdin'] = open(infile, 'rb')
42 if pipeline or capture:
43 kwargs['stdout'] = subprocess.PIPE
44 elif outfile:
45 kwargs['stdout'] = open(outfile, 'wb')
46 if hide_stderr:
47 kwargs['stderr'] = open('/dev/null', 'wb')
48
49 last_pipe = subprocess.Popen(cmd, **kwargs)
50
51 if capture:
52 ret = last_pipe.communicate()[0]
53 if not ret:
54 return None
55 elif oneline:
56 return ret.rstrip('\r\n')
57 else:
58 return ret
59 else:
60 return os.waitpid(last_pipe.pid, 0)[1] == 0
61
62def Output(*cmd):
63 return RunPipe([cmd], capture=True)
64
65def OutputOneLine(*cmd):
66 return RunPipe([cmd], capture=True, oneline=True)
67
68def Run(*cmd, **kwargs):
69 return RunPipe([cmd], **kwargs)
70
71def RunList(cmd):
72 return RunPipe([cmd], capture=True)