blob: ac44555dcf5a038478ca172669035d974910382d [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):
37 super(CalledProcessError, self).__init__(returncode, cmd)
38 self.stdout = stdout
39 self.stderr = stderr
40 self.cwd = cwd
41
42 def __str__(self):
43 out = 'Command %s returned non-zero exit status %s' % (
44 ' '.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')
250 # Popen() can throw OSError when cwd or args[0] doesn't exist. Let it go
251 # through
252 raise
maruel@chromium.org4860f052011-03-25 20:34:38 +0000253
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000254 def _tee_threads(self, input): # pylint: disable=W0622
255 """Does I/O for a process's pipes using threads.
256
257 It's the simplest and slowest implementation. Expect very slow behavior.
258
259 If there is a callback and it doesn't keep up with the calls, the timeout
260 effectiveness will be delayed accordingly.
261 """
262 # Queue of either of <threadname> when done or (<threadname>, data). In
263 # theory we would like to limit to ~64kb items to not cause large memory
264 # usage when the callback blocks. It is not done because it slows down
265 # processing on OSX10.6 by a factor of 2x, making it even slower than
266 # Windows! Revisit this decision if it becomes a problem, e.g. crash
267 # because of memory exhaustion.
268 queue = Queue.Queue()
269 done = threading.Event()
szager@chromium.org12b07e72013-05-03 22:06:34 +0000270 nag = None
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000271
272 def write_stdin():
273 try:
274 stdin_io = cStringIO.StringIO(input)
275 while True:
276 data = stdin_io.read(1024)
277 if data:
278 self.stdin.write(data)
279 else:
280 self.stdin.close()
281 break
282 finally:
283 queue.put('stdin')
284
285 def _queue_pipe_read(pipe, name):
286 """Queues characters read from a pipe into a queue."""
287 try:
288 while True:
289 data = pipe.read(1)
290 if not data:
291 break
szager@chromium.org12b07e72013-05-03 22:06:34 +0000292 if nag:
293 nag.event()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000294 queue.put((name, data))
295 finally:
296 queue.put(name)
297
298 def timeout_fn():
299 try:
300 done.wait(self.timeout)
301 finally:
302 queue.put('timeout')
303
304 def wait_fn():
305 try:
306 self.wait()
307 finally:
308 queue.put('wait')
309
310 # Starts up to 5 threads:
311 # Wait for the process to quit
312 # Read stdout
313 # Read stderr
314 # Write stdin
315 # Timeout
316 threads = {
317 'wait': threading.Thread(target=wait_fn),
318 }
319 if self.timeout is not None:
320 threads['timeout'] = threading.Thread(target=timeout_fn)
321 if self.stdout_cb:
322 threads['stdout'] = threading.Thread(
323 target=_queue_pipe_read, args=(self.stdout, 'stdout'))
324 if self.stderr_cb:
325 threads['stderr'] = threading.Thread(
326 target=_queue_pipe_read, args=(self.stderr, 'stderr'))
327 if input:
328 threads['stdin'] = threading.Thread(target=write_stdin)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000329 elif self.stdin:
330 # Pipe but no input, make sure it's closed.
331 self.stdin.close()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000332 for t in threads.itervalues():
333 t.start()
334
szager@chromium.orge0558e62013-05-02 02:48:51 +0000335 if self.nag_timer:
szager@chromium.org12b07e72013-05-03 22:06:34 +0000336 def _nag_cb(elapsed):
337 logging.warn(' No output for %.0f seconds from command:' % elapsed)
338 logging.warn(' %s' % self.cmd_str)
339 if (self.nag_max and
340 int('%.0f' % (elapsed / self.nag_timer)) >= self.nag_max):
341 queue.put('timeout')
342 done.set() # Must do this so that timeout thread stops waiting.
343 nag = NagTimer(self.nag_timer, _nag_cb)
344 nag.start()
szager@chromium.orge0558e62013-05-02 02:48:51 +0000345
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000346 timed_out = False
347 try:
348 # This thread needs to be optimized for speed.
349 while threads:
350 item = queue.get()
maruel@chromium.orgcd8d8e12012-10-03 17:16:25 +0000351 if item[0] == 'stdout':
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000352 self.stdout_cb(item[1])
maruel@chromium.orgcd8d8e12012-10-03 17:16:25 +0000353 elif item[0] == 'stderr':
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000354 self.stderr_cb(item[1])
355 else:
356 # A thread terminated.
szager@chromium.org12b07e72013-05-03 22:06:34 +0000357 if item in threads:
358 threads[item].join()
359 del threads[item]
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000360 if item == 'wait':
361 # Terminate the timeout thread if necessary.
362 done.set()
363 elif item == 'timeout' and not timed_out and self.poll() is None:
szager@chromium.org12b07e72013-05-03 22:06:34 +0000364 logging.debug('Timed out after %.0fs: killing' % (
365 time.time() - self.start))
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000366 self.kill()
367 timed_out = True
368 finally:
369 # Stop the threads.
370 done.set()
szager@chromium.org12b07e72013-05-03 22:06:34 +0000371 if nag:
372 nag.cancel()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000373 if 'wait' in threads:
374 # Accelerate things, otherwise it would hang until the child process is
375 # done.
376 logging.debug('Killing child because of an exception')
377 self.kill()
378 # Join threads.
379 for thread in threads.itervalues():
380 thread.join()
381 if timed_out:
382 self.returncode = TIMED_OUT
383
szager@chromium.orge0558e62013-05-02 02:48:51 +0000384 # pylint: disable=W0221,W0622
szager@chromium.org12b07e72013-05-03 22:06:34 +0000385 def communicate(self, input=None, timeout=None, nag_timer=None,
386 nag_max=None):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000387 """Adds timeout and callbacks support.
388
389 Returns (stdout, stderr) like subprocess.Popen().communicate().
390
391 - The process will be killed after |timeout| seconds and returncode set to
392 TIMED_OUT.
szager@chromium.orge0558e62013-05-02 02:48:51 +0000393 - If the subprocess runs for |nag_timer| seconds without producing terminal
394 output, print a warning to stderr.
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000395 """
396 self.timeout = timeout
szager@chromium.orge0558e62013-05-02 02:48:51 +0000397 self.nag_timer = nag_timer
szager@chromium.org12b07e72013-05-03 22:06:34 +0000398 self.nag_max = nag_max
szager@chromium.orge0558e62013-05-02 02:48:51 +0000399 if (not self.timeout and not self.nag_timer and
400 not self.stdout_cb and not self.stderr_cb):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000401 return super(Popen, self).communicate(input)
402
403 if self.timeout and self.shell:
404 raise TypeError(
405 'Using timeout and shell simultaneously will cause a process leak '
406 'since the shell will be killed instead of the child process.')
407
408 stdout = None
409 stderr = None
410 # Convert to a lambda to workaround python's deadlock.
411 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000412 # When the pipe fills up, it would deadlock this process.
413 if self.stdout and not self.stdout_cb and not self.stdout_is_void:
414 stdout = []
415 self.stdout_cb = stdout.append
416 if self.stderr and not self.stderr_cb and not self.stderr_is_void:
417 stderr = []
418 self.stderr_cb = stderr.append
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000419 self._tee_threads(input)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000420 if stdout is not None:
421 stdout = ''.join(stdout)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000422 if stderr is not None:
423 stderr = ''.join(stderr)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000424 return (stdout, stderr)
425
maruel@chromium.org4860f052011-03-25 20:34:38 +0000426
szager@chromium.org12b07e72013-05-03 22:06:34 +0000427def communicate(args, timeout=None, nag_timer=None, nag_max=None, **kwargs):
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000428 """Wraps subprocess.Popen().communicate() and add timeout support.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000429
maruel@chromium.org421982f2011-04-01 17:38:06 +0000430 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000431
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000432 - The process will be killed after |timeout| seconds and returncode set to
433 TIMED_OUT.
szager@chromium.orge0558e62013-05-02 02:48:51 +0000434 - If the subprocess runs for |nag_timer| seconds without producing terminal
435 output, print a warning to stderr.
maruel@chromium.org421982f2011-04-01 17:38:06 +0000436 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000437 """
438 stdin = kwargs.pop('stdin', None)
439 if stdin is not None:
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000440 if isinstance(stdin, basestring):
maruel@chromium.org0d5ef242011-04-18 13:52:58 +0000441 # When stdin is passed as an argument, use it as the actual input data and
442 # set the Popen() parameter accordingly.
443 kwargs['stdin'] = PIPE
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000444 else:
445 kwargs['stdin'] = stdin
446 stdin = None
maruel@chromium.org4860f052011-03-25 20:34:38 +0000447
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000448 proc = Popen(args, **kwargs)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000449 if stdin:
szager@chromium.orge0558e62013-05-02 02:48:51 +0000450 return proc.communicate(stdin, timeout, nag_timer), proc.returncode
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000451 else:
szager@chromium.orge0558e62013-05-02 02:48:51 +0000452 return proc.communicate(None, timeout, nag_timer), proc.returncode
maruel@chromium.org4860f052011-03-25 20:34:38 +0000453
454
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000455def call(args, **kwargs):
456 """Emulates subprocess.call().
457
458 Automatically convert stdout=PIPE or stderr=PIPE to VOID.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000459 In no case they can be returned since no code path raises
460 subprocess2.CalledProcessError.
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000461 """
462 if kwargs.get('stdout') == PIPE:
463 kwargs['stdout'] = VOID
464 if kwargs.get('stderr') == PIPE:
465 kwargs['stderr'] = VOID
466 return communicate(args, **kwargs)[1]
467
468
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000469def check_call_out(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000470 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000471
maruel@chromium.org421982f2011-04-01 17:38:06 +0000472 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000473 """
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000474 out, returncode = communicate(args, **kwargs)
maruel@chromium.org4860f052011-03-25 20:34:38 +0000475 if returncode:
476 raise CalledProcessError(
477 returncode, args, kwargs.get('cwd'), out[0], out[1])
478 return out
479
480
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000481def check_call(args, **kwargs):
482 """Emulate subprocess.check_call()."""
483 check_call_out(args, **kwargs)
484 return 0
485
486
maruel@chromium.org4860f052011-03-25 20:34:38 +0000487def capture(args, **kwargs):
488 """Captures stdout of a process call and returns it.
489
maruel@chromium.org421982f2011-04-01 17:38:06 +0000490 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000491
maruel@chromium.org421982f2011-04-01 17:38:06 +0000492 - Discards returncode.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000493 - Blocks stdin by default if not specified since no output will be visible.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000494 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000495 kwargs.setdefault('stdin', VOID)
496
497 # Like check_output, deny the caller from using stdout arg.
498 return communicate(args, stdout=PIPE, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000499
500
501def check_output(args, **kwargs):
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000502 """Emulates subprocess.check_output().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000503
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000504 Captures stdout of a process call and returns stdout only.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000505
maruel@chromium.org421982f2011-04-01 17:38:06 +0000506 - Throws if return code is not 0.
507 - Works even prior to python 2.7.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000508 - Blocks stdin by default if not specified since no output will be visible.
509 - As per doc, "The stdout argument is not allowed as it is used internally."
maruel@chromium.org4860f052011-03-25 20:34:38 +0000510 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000511 kwargs.setdefault('stdin', VOID)
maruel@chromium.orgdb59bfc2011-11-30 14:03:14 +0000512 if 'stdout' in kwargs:
513 raise ValueError('stdout argument not allowed, it will be overridden.')
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000514 return check_call_out(args, stdout=PIPE, **kwargs)[0]