blob: 21e34878516b20ca7b260420d9a526cd0eb40b4a [file] [log] [blame]
maruel@chromium.org4860f052011-03-25 20:34:38 +00001# coding=utf8
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
maruel@chromium.org94c712f2011-12-01 15:04:57 +000010import cStringIO
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000011import errno
maruel@chromium.org4860f052011-03-25 20:34:38 +000012import logging
13import os
maruel@chromium.org94c712f2011-12-01 15:04:57 +000014import Queue
maruel@chromium.org4860f052011-03-25 20:34:38 +000015import subprocess
16import sys
maruel@chromium.org4860f052011-03-25 20:34:38 +000017import time
18import threading
19
maruel@chromium.orga8e81632011-12-01 00:35:24 +000020
maruel@chromium.org4860f052011-03-25 20:34:38 +000021# Constants forwarded from subprocess.
22PIPE = subprocess.PIPE
23STDOUT = subprocess.STDOUT
maruel@chromium.org421982f2011-04-01 17:38:06 +000024# Sends stdout or stderr to os.devnull.
maruel@chromium.org0d5ef242011-04-18 13:52:58 +000025VOID = object()
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000026# Error code when a process was killed because it timed out.
27TIMED_OUT = -2001
maruel@chromium.org4860f052011-03-25 20:34:38 +000028
29# Globals.
30# Set to True if you somehow need to disable this hack.
31SUBPROCESS_CLEANUP_HACKED = False
32
33
34class CalledProcessError(subprocess.CalledProcessError):
35 """Augment the standard exception with more data."""
36 def __init__(self, returncode, cmd, cwd, stdout, stderr):
tandrii@chromium.orgc15fe572014-09-19 11:51:43 +000037 super(CalledProcessError, self).__init__(returncode, cmd, output=stdout)
38 self.stdout = self.output # for backward compatibility.
maruel@chromium.org4860f052011-03-25 20:34:38 +000039 self.stderr = stderr
40 self.cwd = cwd
41
42 def __str__(self):
sbc@chromium.org217330f2015-06-01 22:10:14 +000043 out = 'Command %r returned non-zero exit status %s' % (
maruel@chromium.org4860f052011-03-25 20:34:38 +000044 ' '.join(self.cmd), self.returncode)
45 if self.cwd:
46 out += ' in ' + self.cwd
47 return '\n'.join(filter(None, (out, self.stdout, self.stderr)))
48
49
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000050class CygwinRebaseError(CalledProcessError):
51 """Occurs when cygwin's fork() emulation fails due to rebased dll."""
52
53
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000054## Utility functions
55
56
57def kill_pid(pid):
58 """Kills a process by its process id."""
59 try:
60 # Unable to import 'module'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000061 # pylint: disable=E1101,F0401
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000062 import signal
63 return os.kill(pid, signal.SIGKILL)
64 except ImportError:
65 pass
66
67
68def kill_win(process):
69 """Kills a process with its windows handle.
70
71 Has no effect on other platforms.
72 """
73 try:
74 # Unable to import 'module'
75 # pylint: disable=F0401
76 import win32process
77 # Access to a protected member _handle of a client class
78 # pylint: disable=W0212
79 return win32process.TerminateProcess(process._handle, -1)
80 except ImportError:
81 pass
82
83
84def add_kill():
85 """Adds kill() method to subprocess.Popen for python <2.6"""
86 if hasattr(subprocess.Popen, 'kill'):
87 return
88
89 if sys.platform == 'win32':
90 subprocess.Popen.kill = kill_win
91 else:
92 subprocess.Popen.kill = lambda process: kill_pid(process.pid)
93
94
maruel@chromium.org4860f052011-03-25 20:34:38 +000095def hack_subprocess():
96 """subprocess functions may throw exceptions when used in multiple threads.
97
98 See http://bugs.python.org/issue1731717 for more information.
99 """
100 global SUBPROCESS_CLEANUP_HACKED
101 if not SUBPROCESS_CLEANUP_HACKED and threading.activeCount() != 1:
102 # Only hack if there is ever multiple threads.
103 # There is no point to leak with only one thread.
104 subprocess._cleanup = lambda: None
105 SUBPROCESS_CLEANUP_HACKED = True
106
107
108def get_english_env(env):
109 """Forces LANG and/or LANGUAGE to be English.
110
111 Forces encoding to utf-8 for subprocesses.
112
113 Returns None if it is unnecessary.
114 """
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +0000115 if sys.platform == 'win32':
116 return None
maruel@chromium.org4860f052011-03-25 20:34:38 +0000117 env = env or os.environ
118
119 # Test if it is necessary at all.
120 is_english = lambda name: env.get(name, 'en').startswith('en')
121
122 if is_english('LANG') and is_english('LANGUAGE'):
123 return None
124
125 # Requires modifications.
126 env = env.copy()
127 def fix_lang(name):
128 if not is_english(name):
129 env[name] = 'en_US.UTF-8'
130 fix_lang('LANG')
131 fix_lang('LANGUAGE')
132 return env
133
134
szager@chromium.org12b07e72013-05-03 22:06:34 +0000135class NagTimer(object):
136 """
137 Triggers a callback when a time interval passes without an event being fired.
138
139 For example, the event could be receiving terminal output from a subprocess;
140 and the callback could print a warning to stderr that the subprocess appeared
141 to be hung.
142 """
143 def __init__(self, interval, cb):
144 self.interval = interval
145 self.cb = cb
146 self.timer = threading.Timer(self.interval, self.fn)
147 self.last_output = self.previous_last_output = 0
148
149 def start(self):
150 self.last_output = self.previous_last_output = time.time()
151 self.timer.start()
152
153 def event(self):
154 self.last_output = time.time()
155
156 def fn(self):
157 now = time.time()
158 if self.last_output == self.previous_last_output:
159 self.cb(now - self.previous_last_output)
160 # Use 0.1 fudge factor, just in case
161 # (self.last_output - now) is very close to zero.
162 sleep_time = (self.last_output - now - 0.1) % self.interval
163 self.previous_last_output = self.last_output
164 self.timer = threading.Timer(sleep_time + 0.1, self.fn)
165 self.timer.start()
166
167 def cancel(self):
168 self.timer.cancel()
169
170
maruel@google.comef77f9e2011-11-24 15:24:02 +0000171class Popen(subprocess.Popen):
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000172 """Wraps subprocess.Popen() with various workarounds.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000173
maruel@chromium.org421982f2011-04-01 17:38:06 +0000174 - Forces English output since it's easier to parse the stdout if it is always
175 in English.
176 - Sets shell=True on windows by default. You can override this by forcing
177 shell parameter to a value.
178 - Adds support for VOID to not buffer when not needed.
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000179 - Adds self.start property.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000180
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000181 Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate
182 exceptions generated by cygwin when it fails trying to emulate fork().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000183 """
maruel@google.comef77f9e2011-11-24 15:24:02 +0000184 def __init__(self, args, **kwargs):
185 # Make sure we hack subprocess if necessary.
186 hack_subprocess()
187 add_kill()
maruel@chromium.org4860f052011-03-25 20:34:38 +0000188
maruel@google.comef77f9e2011-11-24 15:24:02 +0000189 env = get_english_env(kwargs.get('env'))
190 if env:
191 kwargs['env'] = env
192 if kwargs.get('shell') is None:
193 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for
194 # the executable, but shell=True makes subprocess on Linux fail when it's
195 # called with a list because it only tries to execute the first item in
196 # the list.
197 kwargs['shell'] = bool(sys.platform=='win32')
maruel@chromium.org4860f052011-03-25 20:34:38 +0000198
maruel@google.comef77f9e2011-11-24 15:24:02 +0000199 if isinstance(args, basestring):
200 tmp_str = args
201 elif isinstance(args, (list, tuple)):
202 tmp_str = ' '.join(args)
203 else:
204 raise CalledProcessError(None, args, kwargs.get('cwd'), None, None)
205 if kwargs.get('cwd', None):
206 tmp_str += '; cwd=%s' % kwargs['cwd']
207 logging.debug(tmp_str)
maruel@chromium.org421982f2011-04-01 17:38:06 +0000208
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000209 self.stdout_cb = None
210 self.stderr_cb = None
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000211 self.stdin_is_void = False
212 self.stdout_is_void = False
213 self.stderr_is_void = False
szager@chromium.orge0558e62013-05-02 02:48:51 +0000214 self.cmd_str = tmp_str
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000215
216 if kwargs.get('stdin') is VOID:
217 kwargs['stdin'] = open(os.devnull, 'r')
218 self.stdin_is_void = True
219
220 for stream in ('stdout', 'stderr'):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000221 if kwargs.get(stream) in (VOID, os.devnull):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000222 kwargs[stream] = open(os.devnull, 'w')
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000223 setattr(self, stream + '_is_void', True)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000224 if callable(kwargs.get(stream)):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000225 setattr(self, stream + '_cb', kwargs[stream])
226 kwargs[stream] = PIPE
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000227
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000228 self.start = time.time()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000229 self.timeout = None
szager@chromium.orge0558e62013-05-02 02:48:51 +0000230 self.nag_timer = None
szager@chromium.org12b07e72013-05-03 22:06:34 +0000231 self.nag_max = None
maruel@chromium.orga8e81632011-12-01 00:35:24 +0000232 self.shell = kwargs.get('shell', None)
maruel@chromium.org14e37ad2011-11-30 20:26:16 +0000233 # Silence pylint on MacOSX
234 self.returncode = None
maruel@chromium.orga8e81632011-12-01 00:35:24 +0000235
maruel@google.comef77f9e2011-11-24 15:24:02 +0000236 try:
237 super(Popen, self).__init__(args, **kwargs)
238 except OSError, e:
239 if e.errno == errno.EAGAIN and sys.platform == 'cygwin':
240 # Convert fork() emulation failure into a CygwinRebaseError().
241 raise CygwinRebaseError(
242 e.errno,
243 args,
244 kwargs.get('cwd'),
245 None,
246 'Visit '
247 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure '
248 'to learn how to fix this error; you need to rebase your cygwin '
249 'dlls')
luqui@chromium.org7f627a92014-03-28 00:57:44 +0000250 # Popen() can throw OSError when cwd or args[0] doesn't exist.
pgervais@chromium.orgfb653b62014-04-29 17:29:18 +0000251 raise OSError('Execution failed with error: %s.\n'
252 'Check that %s or %s exist and have execution permission.'
253 % (str(e), kwargs.get('cwd'), args[0]))
maruel@chromium.org4860f052011-03-25 20:34:38 +0000254
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000255 def _tee_threads(self, input): # pylint: disable=W0622
256 """Does I/O for a process's pipes using threads.
257
258 It's the simplest and slowest implementation. Expect very slow behavior.
259
260 If there is a callback and it doesn't keep up with the calls, the timeout
261 effectiveness will be delayed accordingly.
262 """
263 # Queue of either of <threadname> when done or (<threadname>, data). In
264 # theory we would like to limit to ~64kb items to not cause large memory
265 # usage when the callback blocks. It is not done because it slows down
266 # processing on OSX10.6 by a factor of 2x, making it even slower than
267 # Windows! Revisit this decision if it becomes a problem, e.g. crash
268 # because of memory exhaustion.
269 queue = Queue.Queue()
270 done = threading.Event()
szager@chromium.org12b07e72013-05-03 22:06:34 +0000271 nag = None
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000272
273 def write_stdin():
274 try:
275 stdin_io = cStringIO.StringIO(input)
276 while True:
277 data = stdin_io.read(1024)
278 if data:
279 self.stdin.write(data)
280 else:
281 self.stdin.close()
282 break
283 finally:
284 queue.put('stdin')
285
286 def _queue_pipe_read(pipe, name):
287 """Queues characters read from a pipe into a queue."""
288 try:
289 while True:
290 data = pipe.read(1)
291 if not data:
292 break
szager@chromium.org12b07e72013-05-03 22:06:34 +0000293 if nag:
294 nag.event()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000295 queue.put((name, data))
296 finally:
297 queue.put(name)
298
299 def timeout_fn():
300 try:
301 done.wait(self.timeout)
302 finally:
303 queue.put('timeout')
304
305 def wait_fn():
306 try:
307 self.wait()
308 finally:
309 queue.put('wait')
310
311 # Starts up to 5 threads:
312 # Wait for the process to quit
313 # Read stdout
314 # Read stderr
315 # Write stdin
316 # Timeout
317 threads = {
318 'wait': threading.Thread(target=wait_fn),
319 }
320 if self.timeout is not None:
321 threads['timeout'] = threading.Thread(target=timeout_fn)
322 if self.stdout_cb:
323 threads['stdout'] = threading.Thread(
324 target=_queue_pipe_read, args=(self.stdout, 'stdout'))
325 if self.stderr_cb:
326 threads['stderr'] = threading.Thread(
327 target=_queue_pipe_read, args=(self.stderr, 'stderr'))
328 if input:
329 threads['stdin'] = threading.Thread(target=write_stdin)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000330 elif self.stdin:
331 # Pipe but no input, make sure it's closed.
332 self.stdin.close()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000333 for t in threads.itervalues():
334 t.start()
335
szager@chromium.orge0558e62013-05-02 02:48:51 +0000336 if self.nag_timer:
szager@chromium.org12b07e72013-05-03 22:06:34 +0000337 def _nag_cb(elapsed):
338 logging.warn(' No output for %.0f seconds from command:' % elapsed)
339 logging.warn(' %s' % self.cmd_str)
340 if (self.nag_max and
341 int('%.0f' % (elapsed / self.nag_timer)) >= self.nag_max):
342 queue.put('timeout')
343 done.set() # Must do this so that timeout thread stops waiting.
344 nag = NagTimer(self.nag_timer, _nag_cb)
345 nag.start()
szager@chromium.orge0558e62013-05-02 02:48:51 +0000346
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000347 timed_out = False
348 try:
349 # This thread needs to be optimized for speed.
350 while threads:
351 item = queue.get()
maruel@chromium.orgcd8d8e12012-10-03 17:16:25 +0000352 if item[0] == 'stdout':
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000353 self.stdout_cb(item[1])
maruel@chromium.orgcd8d8e12012-10-03 17:16:25 +0000354 elif item[0] == 'stderr':
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000355 self.stderr_cb(item[1])
356 else:
357 # A thread terminated.
szager@chromium.org12b07e72013-05-03 22:06:34 +0000358 if item in threads:
359 threads[item].join()
360 del threads[item]
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000361 if item == 'wait':
362 # Terminate the timeout thread if necessary.
363 done.set()
364 elif item == 'timeout' and not timed_out and self.poll() is None:
szager@chromium.org12b07e72013-05-03 22:06:34 +0000365 logging.debug('Timed out after %.0fs: killing' % (
366 time.time() - self.start))
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000367 self.kill()
368 timed_out = True
369 finally:
370 # Stop the threads.
371 done.set()
szager@chromium.org12b07e72013-05-03 22:06:34 +0000372 if nag:
373 nag.cancel()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000374 if 'wait' in threads:
375 # Accelerate things, otherwise it would hang until the child process is
376 # done.
377 logging.debug('Killing child because of an exception')
378 self.kill()
379 # Join threads.
380 for thread in threads.itervalues():
381 thread.join()
382 if timed_out:
383 self.returncode = TIMED_OUT
384
szager@chromium.orge0558e62013-05-02 02:48:51 +0000385 # pylint: disable=W0221,W0622
szager@chromium.org12b07e72013-05-03 22:06:34 +0000386 def communicate(self, input=None, timeout=None, nag_timer=None,
387 nag_max=None):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000388 """Adds timeout and callbacks support.
389
390 Returns (stdout, stderr) like subprocess.Popen().communicate().
391
392 - The process will be killed after |timeout| seconds and returncode set to
393 TIMED_OUT.
szager@chromium.orge0558e62013-05-02 02:48:51 +0000394 - If the subprocess runs for |nag_timer| seconds without producing terminal
395 output, print a warning to stderr.
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000396 """
397 self.timeout = timeout
szager@chromium.orge0558e62013-05-02 02:48:51 +0000398 self.nag_timer = nag_timer
szager@chromium.org12b07e72013-05-03 22:06:34 +0000399 self.nag_max = nag_max
szager@chromium.orge0558e62013-05-02 02:48:51 +0000400 if (not self.timeout and not self.nag_timer and
401 not self.stdout_cb and not self.stderr_cb):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000402 return super(Popen, self).communicate(input)
403
404 if self.timeout and self.shell:
405 raise TypeError(
406 'Using timeout and shell simultaneously will cause a process leak '
407 'since the shell will be killed instead of the child process.')
408
409 stdout = None
410 stderr = None
411 # Convert to a lambda to workaround python's deadlock.
412 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000413 # When the pipe fills up, it would deadlock this process.
414 if self.stdout and not self.stdout_cb and not self.stdout_is_void:
415 stdout = []
416 self.stdout_cb = stdout.append
417 if self.stderr and not self.stderr_cb and not self.stderr_is_void:
418 stderr = []
419 self.stderr_cb = stderr.append
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000420 self._tee_threads(input)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000421 if stdout is not None:
422 stdout = ''.join(stdout)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000423 if stderr is not None:
424 stderr = ''.join(stderr)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000425 return (stdout, stderr)
426
maruel@chromium.org4860f052011-03-25 20:34:38 +0000427
szager@chromium.org12b07e72013-05-03 22:06:34 +0000428def communicate(args, timeout=None, nag_timer=None, nag_max=None, **kwargs):
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000429 """Wraps subprocess.Popen().communicate() and add timeout support.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000430
maruel@chromium.org421982f2011-04-01 17:38:06 +0000431 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000432
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000433 - The process will be killed after |timeout| seconds and returncode set to
434 TIMED_OUT.
szager@chromium.orge0558e62013-05-02 02:48:51 +0000435 - If the subprocess runs for |nag_timer| seconds without producing terminal
436 output, print a warning to stderr.
maruel@chromium.org421982f2011-04-01 17:38:06 +0000437 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000438 """
439 stdin = kwargs.pop('stdin', None)
440 if stdin is not None:
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000441 if isinstance(stdin, basestring):
maruel@chromium.org0d5ef242011-04-18 13:52:58 +0000442 # When stdin is passed as an argument, use it as the actual input data and
443 # set the Popen() parameter accordingly.
444 kwargs['stdin'] = PIPE
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000445 else:
446 kwargs['stdin'] = stdin
447 stdin = None
maruel@chromium.org4860f052011-03-25 20:34:38 +0000448
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000449 proc = Popen(args, **kwargs)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000450 if stdin:
szager@chromium.orge0558e62013-05-02 02:48:51 +0000451 return proc.communicate(stdin, timeout, nag_timer), proc.returncode
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000452 else:
szager@chromium.orge0558e62013-05-02 02:48:51 +0000453 return proc.communicate(None, timeout, nag_timer), proc.returncode
maruel@chromium.org4860f052011-03-25 20:34:38 +0000454
455
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000456def call(args, **kwargs):
457 """Emulates subprocess.call().
458
459 Automatically convert stdout=PIPE or stderr=PIPE to VOID.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000460 In no case they can be returned since no code path raises
461 subprocess2.CalledProcessError.
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000462 """
463 if kwargs.get('stdout') == PIPE:
464 kwargs['stdout'] = VOID
465 if kwargs.get('stderr') == PIPE:
466 kwargs['stderr'] = VOID
467 return communicate(args, **kwargs)[1]
468
469
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000470def check_call_out(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000471 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000472
maruel@chromium.org421982f2011-04-01 17:38:06 +0000473 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000474 """
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000475 out, returncode = communicate(args, **kwargs)
maruel@chromium.org4860f052011-03-25 20:34:38 +0000476 if returncode:
477 raise CalledProcessError(
478 returncode, args, kwargs.get('cwd'), out[0], out[1])
479 return out
480
481
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000482def check_call(args, **kwargs):
483 """Emulate subprocess.check_call()."""
484 check_call_out(args, **kwargs)
485 return 0
486
487
maruel@chromium.org4860f052011-03-25 20:34:38 +0000488def capture(args, **kwargs):
489 """Captures stdout of a process call and returns it.
490
maruel@chromium.org421982f2011-04-01 17:38:06 +0000491 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000492
maruel@chromium.org421982f2011-04-01 17:38:06 +0000493 - Discards returncode.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000494 - Blocks stdin by default if not specified since no output will be visible.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000495 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000496 kwargs.setdefault('stdin', VOID)
497
498 # Like check_output, deny the caller from using stdout arg.
499 return communicate(args, stdout=PIPE, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000500
501
502def check_output(args, **kwargs):
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000503 """Emulates subprocess.check_output().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000504
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000505 Captures stdout of a process call and returns stdout only.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000506
maruel@chromium.org421982f2011-04-01 17:38:06 +0000507 - Throws if return code is not 0.
508 - Works even prior to python 2.7.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000509 - Blocks stdin by default if not specified since no output will be visible.
510 - As per doc, "The stdout argument is not allowed as it is used internally."
maruel@chromium.org4860f052011-03-25 20:34:38 +0000511 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000512 kwargs.setdefault('stdin', VOID)
maruel@chromium.orgdb59bfc2011-11-30 14:03:14 +0000513 if 'stdout' in kwargs:
pgervais@chromium.org022d06e2014-04-29 17:08:12 +0000514 raise ValueError('stdout argument not allowed, it would be overridden.')
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000515 return check_call_out(args, stdout=PIPE, **kwargs)[0]