blob: 34fdee8289161dd5796d069685d2f43e0ae20727 [file] [log] [blame]
Raul Tambrea04028c2019-05-13 17:23:36 +00001# coding=utf-8
maruel@chromium.org4f6852c2012-04-20 20:39:20 +00002# Copyright (c) 2012 The Chromium Authors. All rights reserved.
maruel@chromium.org4860f052011-03-25 20:34:38 +00003# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5"""Collection of subprocess wrapper functions.
6
7In theory you shouldn't need anything else in subprocess, or this module failed.
8"""
9
John Budorick9875e182018-12-05 22:57:31 +000010import codecs
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000011import errno
Raul Tambreb946b232019-03-26 14:48:46 +000012import io
maruel@chromium.org4860f052011-03-25 20:34:38 +000013import logging
14import os
Raul Tambreb946b232019-03-26 14:48:46 +000015
16try:
17 import Queue
18except ImportError: # For Py3 compatibility
19 import queue as Queue
20
maruel@chromium.org4860f052011-03-25 20:34:38 +000021import subprocess
22import sys
maruel@chromium.org4860f052011-03-25 20:34:38 +000023import time
24import threading
25
John Budorick9875e182018-12-05 22:57:31 +000026# Cache the string-escape codec to ensure subprocess can find it later.
27# See crbug.com/912292#c2 for context.
Raul Tambreb946b232019-03-26 14:48:46 +000028if sys.version_info.major == 2:
29 codecs.lookup('string-escape')
maruel@chromium.orga8e81632011-12-01 00:35:24 +000030
Aaron Gableac9b0f32019-04-18 17:38:37 +000031# TODO(crbug.com/953884): Remove this when python3 migration is done.
32try:
33 basestring
34except NameError:
35 # pylint: disable=redefined-builtin
36 basestring = str
37
38
maruel@chromium.org4860f052011-03-25 20:34:38 +000039# Constants forwarded from subprocess.
40PIPE = subprocess.PIPE
41STDOUT = subprocess.STDOUT
maruel@chromium.org421982f2011-04-01 17:38:06 +000042# Sends stdout or stderr to os.devnull.
maruel@chromium.org0d5ef242011-04-18 13:52:58 +000043VOID = object()
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000044# Error code when a process was killed because it timed out.
45TIMED_OUT = -2001
maruel@chromium.org4860f052011-03-25 20:34:38 +000046
maruel@chromium.org4860f052011-03-25 20:34:38 +000047
48class CalledProcessError(subprocess.CalledProcessError):
49 """Augment the standard exception with more data."""
50 def __init__(self, returncode, cmd, cwd, stdout, stderr):
tandrii@chromium.orgc15fe572014-09-19 11:51:43 +000051 super(CalledProcessError, self).__init__(returncode, cmd, output=stdout)
52 self.stdout = self.output # for backward compatibility.
maruel@chromium.org4860f052011-03-25 20:34:38 +000053 self.stderr = stderr
54 self.cwd = cwd
55
56 def __str__(self):
sbc@chromium.org217330f2015-06-01 22:10:14 +000057 out = 'Command %r returned non-zero exit status %s' % (
maruel@chromium.org4860f052011-03-25 20:34:38 +000058 ' '.join(self.cmd), self.returncode)
59 if self.cwd:
60 out += ' in ' + self.cwd
61 return '\n'.join(filter(None, (out, self.stdout, self.stderr)))
62
63
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000064class CygwinRebaseError(CalledProcessError):
65 """Occurs when cygwin's fork() emulation fails due to rebased dll."""
66
67
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000068## Utility functions
69
70
71def kill_pid(pid):
72 """Kills a process by its process id."""
73 try:
74 # Unable to import 'module'
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080075 # pylint: disable=no-member,F0401
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000076 import signal
Raul Tambree99d4b42019-05-24 18:34:41 +000077 return os.kill(pid, signal.SIGTERM)
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000078 except ImportError:
79 pass
80
81
maruel@chromium.org4860f052011-03-25 20:34:38 +000082def get_english_env(env):
83 """Forces LANG and/or LANGUAGE to be English.
84
85 Forces encoding to utf-8 for subprocesses.
86
87 Returns None if it is unnecessary.
88 """
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000089 if sys.platform == 'win32':
90 return None
maruel@chromium.org4860f052011-03-25 20:34:38 +000091 env = env or os.environ
92
93 # Test if it is necessary at all.
94 is_english = lambda name: env.get(name, 'en').startswith('en')
95
96 if is_english('LANG') and is_english('LANGUAGE'):
97 return None
98
99 # Requires modifications.
100 env = env.copy()
101 def fix_lang(name):
102 if not is_english(name):
103 env[name] = 'en_US.UTF-8'
104 fix_lang('LANG')
105 fix_lang('LANGUAGE')
106 return env
107
108
szager@chromium.org12b07e72013-05-03 22:06:34 +0000109class NagTimer(object):
110 """
111 Triggers a callback when a time interval passes without an event being fired.
112
113 For example, the event could be receiving terminal output from a subprocess;
114 and the callback could print a warning to stderr that the subprocess appeared
115 to be hung.
116 """
117 def __init__(self, interval, cb):
118 self.interval = interval
119 self.cb = cb
120 self.timer = threading.Timer(self.interval, self.fn)
121 self.last_output = self.previous_last_output = 0
122
123 def start(self):
124 self.last_output = self.previous_last_output = time.time()
125 self.timer.start()
126
127 def event(self):
128 self.last_output = time.time()
129
130 def fn(self):
131 now = time.time()
132 if self.last_output == self.previous_last_output:
133 self.cb(now - self.previous_last_output)
134 # Use 0.1 fudge factor, just in case
135 # (self.last_output - now) is very close to zero.
136 sleep_time = (self.last_output - now - 0.1) % self.interval
137 self.previous_last_output = self.last_output
138 self.timer = threading.Timer(sleep_time + 0.1, self.fn)
139 self.timer.start()
140
141 def cancel(self):
142 self.timer.cancel()
143
144
maruel@google.comef77f9e2011-11-24 15:24:02 +0000145class Popen(subprocess.Popen):
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000146 """Wraps subprocess.Popen() with various workarounds.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000147
maruel@chromium.org421982f2011-04-01 17:38:06 +0000148 - Forces English output since it's easier to parse the stdout if it is always
149 in English.
150 - Sets shell=True on windows by default. You can override this by forcing
151 shell parameter to a value.
152 - Adds support for VOID to not buffer when not needed.
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000153 - Adds self.start property.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000154
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000155 Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate
156 exceptions generated by cygwin when it fails trying to emulate fork().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000157 """
torne@chromium.org434e7902015-09-15 09:57:01 +0000158 # subprocess.Popen.__init__() is not threadsafe; there is a race between
159 # creating the exec-error pipe for the child and setting it to CLOEXEC during
160 # which another thread can fork and cause the pipe to be inherited by its
161 # descendents, which will cause the current Popen to hang until all those
162 # descendents exit. Protect this with a lock so that only one fork/exec can
163 # happen at a time.
164 popen_lock = threading.Lock()
165
maruel@google.comef77f9e2011-11-24 15:24:02 +0000166 def __init__(self, args, **kwargs):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000167 env = get_english_env(kwargs.get('env'))
168 if env:
169 kwargs['env'] = env
170 if kwargs.get('shell') is None:
171 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for
172 # the executable, but shell=True makes subprocess on Linux fail when it's
173 # called with a list because it only tries to execute the first item in
174 # the list.
175 kwargs['shell'] = bool(sys.platform=='win32')
maruel@chromium.org4860f052011-03-25 20:34:38 +0000176
Aaron Gableac9b0f32019-04-18 17:38:37 +0000177 if isinstance(args, basestring):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000178 tmp_str = args
179 elif isinstance(args, (list, tuple)):
180 tmp_str = ' '.join(args)
181 else:
182 raise CalledProcessError(None, args, kwargs.get('cwd'), None, None)
183 if kwargs.get('cwd', None):
184 tmp_str += '; cwd=%s' % kwargs['cwd']
185 logging.debug(tmp_str)
maruel@chromium.org421982f2011-04-01 17:38:06 +0000186
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000187 self.stdout_cb = None
188 self.stderr_cb = None
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000189 self.stdin_is_void = False
190 self.stdout_is_void = False
191 self.stderr_is_void = False
szager@chromium.orge0558e62013-05-02 02:48:51 +0000192 self.cmd_str = tmp_str
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000193
194 if kwargs.get('stdin') is VOID:
195 kwargs['stdin'] = open(os.devnull, 'r')
196 self.stdin_is_void = True
197
198 for stream in ('stdout', 'stderr'):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000199 if kwargs.get(stream) in (VOID, os.devnull):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000200 kwargs[stream] = open(os.devnull, 'w')
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000201 setattr(self, stream + '_is_void', True)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000202 if callable(kwargs.get(stream)):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000203 setattr(self, stream + '_cb', kwargs[stream])
204 kwargs[stream] = PIPE
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000205
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000206 self.start = time.time()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000207 self.timeout = None
szager@chromium.orge0558e62013-05-02 02:48:51 +0000208 self.nag_timer = None
szager@chromium.org12b07e72013-05-03 22:06:34 +0000209 self.nag_max = None
maruel@chromium.orga8e81632011-12-01 00:35:24 +0000210 self.shell = kwargs.get('shell', None)
maruel@chromium.org14e37ad2011-11-30 20:26:16 +0000211 # Silence pylint on MacOSX
212 self.returncode = None
maruel@chromium.orga8e81632011-12-01 00:35:24 +0000213
maruel@google.comef77f9e2011-11-24 15:24:02 +0000214 try:
torne@chromium.org434e7902015-09-15 09:57:01 +0000215 with self.popen_lock:
216 super(Popen, self).__init__(args, **kwargs)
Raul Tambreb946b232019-03-26 14:48:46 +0000217 except OSError as e:
maruel@google.comef77f9e2011-11-24 15:24:02 +0000218 if e.errno == errno.EAGAIN and sys.platform == 'cygwin':
219 # Convert fork() emulation failure into a CygwinRebaseError().
220 raise CygwinRebaseError(
221 e.errno,
222 args,
223 kwargs.get('cwd'),
224 None,
225 'Visit '
226 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure '
227 'to learn how to fix this error; you need to rebase your cygwin '
228 'dlls')
luqui@chromium.org7f627a92014-03-28 00:57:44 +0000229 # Popen() can throw OSError when cwd or args[0] doesn't exist.
pgervais@chromium.orgfb653b62014-04-29 17:29:18 +0000230 raise OSError('Execution failed with error: %s.\n'
231 'Check that %s or %s exist and have execution permission.'
232 % (str(e), kwargs.get('cwd'), args[0]))
maruel@chromium.org4860f052011-03-25 20:34:38 +0000233
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800234 def _tee_threads(self, input): # pylint: disable=redefined-builtin
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000235 """Does I/O for a process's pipes using threads.
236
237 It's the simplest and slowest implementation. Expect very slow behavior.
238
239 If there is a callback and it doesn't keep up with the calls, the timeout
240 effectiveness will be delayed accordingly.
241 """
242 # Queue of either of <threadname> when done or (<threadname>, data). In
243 # theory we would like to limit to ~64kb items to not cause large memory
244 # usage when the callback blocks. It is not done because it slows down
245 # processing on OSX10.6 by a factor of 2x, making it even slower than
246 # Windows! Revisit this decision if it becomes a problem, e.g. crash
247 # because of memory exhaustion.
248 queue = Queue.Queue()
249 done = threading.Event()
szager@chromium.org12b07e72013-05-03 22:06:34 +0000250 nag = None
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000251
252 def write_stdin():
253 try:
Raul Tambreb946b232019-03-26 14:48:46 +0000254 stdin_io = io.BytesIO(input)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000255 while True:
256 data = stdin_io.read(1024)
257 if data:
258 self.stdin.write(data)
259 else:
260 self.stdin.close()
261 break
262 finally:
263 queue.put('stdin')
264
265 def _queue_pipe_read(pipe, name):
266 """Queues characters read from a pipe into a queue."""
267 try:
268 while True:
269 data = pipe.read(1)
270 if not data:
271 break
szager@chromium.org12b07e72013-05-03 22:06:34 +0000272 if nag:
273 nag.event()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000274 queue.put((name, data))
275 finally:
276 queue.put(name)
277
278 def timeout_fn():
279 try:
280 done.wait(self.timeout)
281 finally:
282 queue.put('timeout')
283
284 def wait_fn():
285 try:
286 self.wait()
287 finally:
288 queue.put('wait')
289
290 # Starts up to 5 threads:
291 # Wait for the process to quit
292 # Read stdout
293 # Read stderr
294 # Write stdin
295 # Timeout
296 threads = {
297 'wait': threading.Thread(target=wait_fn),
298 }
299 if self.timeout is not None:
300 threads['timeout'] = threading.Thread(target=timeout_fn)
301 if self.stdout_cb:
302 threads['stdout'] = threading.Thread(
303 target=_queue_pipe_read, args=(self.stdout, 'stdout'))
304 if self.stderr_cb:
305 threads['stderr'] = threading.Thread(
306 target=_queue_pipe_read, args=(self.stderr, 'stderr'))
307 if input:
308 threads['stdin'] = threading.Thread(target=write_stdin)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000309 elif self.stdin:
310 # Pipe but no input, make sure it's closed.
311 self.stdin.close()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000312 for t in threads.itervalues():
313 t.start()
314
szager@chromium.orge0558e62013-05-02 02:48:51 +0000315 if self.nag_timer:
szager@chromium.org12b07e72013-05-03 22:06:34 +0000316 def _nag_cb(elapsed):
317 logging.warn(' No output for %.0f seconds from command:' % elapsed)
318 logging.warn(' %s' % self.cmd_str)
319 if (self.nag_max and
320 int('%.0f' % (elapsed / self.nag_timer)) >= self.nag_max):
321 queue.put('timeout')
322 done.set() # Must do this so that timeout thread stops waiting.
323 nag = NagTimer(self.nag_timer, _nag_cb)
324 nag.start()
szager@chromium.orge0558e62013-05-02 02:48:51 +0000325
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000326 timed_out = False
327 try:
328 # This thread needs to be optimized for speed.
329 while threads:
330 item = queue.get()
maruel@chromium.orgcd8d8e12012-10-03 17:16:25 +0000331 if item[0] == 'stdout':
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000332 self.stdout_cb(item[1])
maruel@chromium.orgcd8d8e12012-10-03 17:16:25 +0000333 elif item[0] == 'stderr':
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000334 self.stderr_cb(item[1])
335 else:
336 # A thread terminated.
szager@chromium.org12b07e72013-05-03 22:06:34 +0000337 if item in threads:
338 threads[item].join()
339 del threads[item]
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000340 if item == 'wait':
341 # Terminate the timeout thread if necessary.
342 done.set()
343 elif item == 'timeout' and not timed_out and self.poll() is None:
szager@chromium.org12b07e72013-05-03 22:06:34 +0000344 logging.debug('Timed out after %.0fs: killing' % (
345 time.time() - self.start))
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000346 self.kill()
347 timed_out = True
348 finally:
349 # Stop the threads.
350 done.set()
szager@chromium.org12b07e72013-05-03 22:06:34 +0000351 if nag:
352 nag.cancel()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000353 if 'wait' in threads:
354 # Accelerate things, otherwise it would hang until the child process is
355 # done.
356 logging.debug('Killing child because of an exception')
357 self.kill()
358 # Join threads.
359 for thread in threads.itervalues():
360 thread.join()
361 if timed_out:
362 self.returncode = TIMED_OUT
363
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800364 # pylint: disable=arguments-differ,W0622
szager@chromium.org12b07e72013-05-03 22:06:34 +0000365 def communicate(self, input=None, timeout=None, nag_timer=None,
366 nag_max=None):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000367 """Adds timeout and callbacks support.
368
369 Returns (stdout, stderr) like subprocess.Popen().communicate().
370
371 - The process will be killed after |timeout| seconds and returncode set to
372 TIMED_OUT.
szager@chromium.orge0558e62013-05-02 02:48:51 +0000373 - If the subprocess runs for |nag_timer| seconds without producing terminal
374 output, print a warning to stderr.
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000375 """
376 self.timeout = timeout
szager@chromium.orge0558e62013-05-02 02:48:51 +0000377 self.nag_timer = nag_timer
szager@chromium.org12b07e72013-05-03 22:06:34 +0000378 self.nag_max = nag_max
szager@chromium.orge0558e62013-05-02 02:48:51 +0000379 if (not self.timeout and not self.nag_timer and
380 not self.stdout_cb and not self.stderr_cb):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000381 return super(Popen, self).communicate(input)
382
383 if self.timeout and self.shell:
384 raise TypeError(
385 'Using timeout and shell simultaneously will cause a process leak '
386 'since the shell will be killed instead of the child process.')
387
388 stdout = None
389 stderr = None
390 # Convert to a lambda to workaround python's deadlock.
391 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000392 # When the pipe fills up, it would deadlock this process.
393 if self.stdout and not self.stdout_cb and not self.stdout_is_void:
394 stdout = []
395 self.stdout_cb = stdout.append
396 if self.stderr and not self.stderr_cb and not self.stderr_is_void:
397 stderr = []
398 self.stderr_cb = stderr.append
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000399 self._tee_threads(input)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000400 if stdout is not None:
401 stdout = ''.join(stdout)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000402 if stderr is not None:
403 stderr = ''.join(stderr)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000404 return (stdout, stderr)
405
maruel@chromium.org4860f052011-03-25 20:34:38 +0000406
szager@chromium.org12b07e72013-05-03 22:06:34 +0000407def communicate(args, timeout=None, nag_timer=None, nag_max=None, **kwargs):
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000408 """Wraps subprocess.Popen().communicate() and add timeout support.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000409
maruel@chromium.org421982f2011-04-01 17:38:06 +0000410 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000411
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000412 - The process will be killed after |timeout| seconds and returncode set to
413 TIMED_OUT.
szager@chromium.orge0558e62013-05-02 02:48:51 +0000414 - If the subprocess runs for |nag_timer| seconds without producing terminal
415 output, print a warning to stderr.
maruel@chromium.org421982f2011-04-01 17:38:06 +0000416 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000417 """
418 stdin = kwargs.pop('stdin', None)
419 if stdin is not None:
Aaron Gableac9b0f32019-04-18 17:38:37 +0000420 if isinstance(stdin, basestring):
maruel@chromium.org0d5ef242011-04-18 13:52:58 +0000421 # When stdin is passed as an argument, use it as the actual input data and
422 # set the Popen() parameter accordingly.
423 kwargs['stdin'] = PIPE
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000424 else:
425 kwargs['stdin'] = stdin
426 stdin = None
maruel@chromium.org4860f052011-03-25 20:34:38 +0000427
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000428 proc = Popen(args, **kwargs)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000429 if stdin:
szager@chromium.orge0558e62013-05-02 02:48:51 +0000430 return proc.communicate(stdin, timeout, nag_timer), proc.returncode
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000431 else:
szager@chromium.orge0558e62013-05-02 02:48:51 +0000432 return proc.communicate(None, timeout, nag_timer), proc.returncode
maruel@chromium.org4860f052011-03-25 20:34:38 +0000433
434
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000435def call(args, **kwargs):
436 """Emulates subprocess.call().
437
438 Automatically convert stdout=PIPE or stderr=PIPE to VOID.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000439 In no case they can be returned since no code path raises
440 subprocess2.CalledProcessError.
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000441 """
442 if kwargs.get('stdout') == PIPE:
443 kwargs['stdout'] = VOID
444 if kwargs.get('stderr') == PIPE:
445 kwargs['stderr'] = VOID
446 return communicate(args, **kwargs)[1]
447
448
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000449def check_call_out(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000450 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000451
maruel@chromium.org421982f2011-04-01 17:38:06 +0000452 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000453 """
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000454 out, returncode = communicate(args, **kwargs)
maruel@chromium.org4860f052011-03-25 20:34:38 +0000455 if returncode:
456 raise CalledProcessError(
457 returncode, args, kwargs.get('cwd'), out[0], out[1])
458 return out
459
460
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000461def check_call(args, **kwargs):
462 """Emulate subprocess.check_call()."""
463 check_call_out(args, **kwargs)
464 return 0
465
466
maruel@chromium.org4860f052011-03-25 20:34:38 +0000467def capture(args, **kwargs):
468 """Captures stdout of a process call and returns it.
469
maruel@chromium.org421982f2011-04-01 17:38:06 +0000470 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000471
maruel@chromium.org421982f2011-04-01 17:38:06 +0000472 - Discards returncode.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000473 - Blocks stdin by default if not specified since no output will be visible.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000474 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000475 kwargs.setdefault('stdin', VOID)
476
477 # Like check_output, deny the caller from using stdout arg.
478 return communicate(args, stdout=PIPE, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000479
480
481def check_output(args, **kwargs):
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000482 """Emulates subprocess.check_output().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000483
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000484 Captures stdout of a process call and returns stdout only.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000485
maruel@chromium.org421982f2011-04-01 17:38:06 +0000486 - Throws if return code is not 0.
487 - Works even prior to python 2.7.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000488 - Blocks stdin by default if not specified since no output will be visible.
489 - As per doc, "The stdout argument is not allowed as it is used internally."
maruel@chromium.org4860f052011-03-25 20:34:38 +0000490 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000491 kwargs.setdefault('stdin', VOID)
maruel@chromium.orgdb59bfc2011-11-30 14:03:14 +0000492 if 'stdout' in kwargs:
pgervais@chromium.org022d06e2014-04-29 17:08:12 +0000493 raise ValueError('stdout argument not allowed, it would be overridden.')
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000494 return check_call_out(args, stdout=PIPE, **kwargs)[0]