blob: 6ec6d50ae0ba98a062645559295b6e2be6b3b424 [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
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
maruel@chromium.org4860f052011-03-25 20:34:38 +000031# Constants forwarded from subprocess.
32PIPE = subprocess.PIPE
33STDOUT = subprocess.STDOUT
maruel@chromium.org421982f2011-04-01 17:38:06 +000034# Sends stdout or stderr to os.devnull.
maruel@chromium.org0d5ef242011-04-18 13:52:58 +000035VOID = object()
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000036# Error code when a process was killed because it timed out.
37TIMED_OUT = -2001
maruel@chromium.org4860f052011-03-25 20:34:38 +000038
39# Globals.
40# Set to True if you somehow need to disable this hack.
41SUBPROCESS_CLEANUP_HACKED = False
42
43
44class CalledProcessError(subprocess.CalledProcessError):
45 """Augment the standard exception with more data."""
46 def __init__(self, returncode, cmd, cwd, stdout, stderr):
tandrii@chromium.orgc15fe572014-09-19 11:51:43 +000047 super(CalledProcessError, self).__init__(returncode, cmd, output=stdout)
48 self.stdout = self.output # for backward compatibility.
maruel@chromium.org4860f052011-03-25 20:34:38 +000049 self.stderr = stderr
50 self.cwd = cwd
51
52 def __str__(self):
sbc@chromium.org217330f2015-06-01 22:10:14 +000053 out = 'Command %r returned non-zero exit status %s' % (
maruel@chromium.org4860f052011-03-25 20:34:38 +000054 ' '.join(self.cmd), self.returncode)
55 if self.cwd:
56 out += ' in ' + self.cwd
57 return '\n'.join(filter(None, (out, self.stdout, self.stderr)))
58
59
maruel@chromium.org1d9f6292011-04-07 14:15:36 +000060class CygwinRebaseError(CalledProcessError):
61 """Occurs when cygwin's fork() emulation fails due to rebased dll."""
62
63
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000064## Utility functions
65
66
67def kill_pid(pid):
68 """Kills a process by its process id."""
69 try:
70 # Unable to import 'module'
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080071 # pylint: disable=no-member,F0401
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000072 import signal
73 return os.kill(pid, signal.SIGKILL)
74 except ImportError:
75 pass
76
77
78def kill_win(process):
79 """Kills a process with its windows handle.
80
81 Has no effect on other platforms.
82 """
83 try:
84 # Unable to import 'module'
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080085 # pylint: disable=import-error
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000086 import win32process
87 # Access to a protected member _handle of a client class
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -080088 # pylint: disable=protected-access
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000089 return win32process.TerminateProcess(process._handle, -1)
90 except ImportError:
91 pass
92
93
94def add_kill():
95 """Adds kill() method to subprocess.Popen for python <2.6"""
96 if hasattr(subprocess.Popen, 'kill'):
97 return
98
99 if sys.platform == 'win32':
100 subprocess.Popen.kill = kill_win
101 else:
102 subprocess.Popen.kill = lambda process: kill_pid(process.pid)
103
104
maruel@chromium.org4860f052011-03-25 20:34:38 +0000105def hack_subprocess():
106 """subprocess functions may throw exceptions when used in multiple threads.
107
108 See http://bugs.python.org/issue1731717 for more information.
109 """
110 global SUBPROCESS_CLEANUP_HACKED
111 if not SUBPROCESS_CLEANUP_HACKED and threading.activeCount() != 1:
112 # Only hack if there is ever multiple threads.
113 # There is no point to leak with only one thread.
114 subprocess._cleanup = lambda: None
115 SUBPROCESS_CLEANUP_HACKED = True
116
117
118def get_english_env(env):
119 """Forces LANG and/or LANGUAGE to be English.
120
121 Forces encoding to utf-8 for subprocesses.
122
123 Returns None if it is unnecessary.
124 """
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +0000125 if sys.platform == 'win32':
126 return None
maruel@chromium.org4860f052011-03-25 20:34:38 +0000127 env = env or os.environ
128
129 # Test if it is necessary at all.
130 is_english = lambda name: env.get(name, 'en').startswith('en')
131
132 if is_english('LANG') and is_english('LANGUAGE'):
133 return None
134
135 # Requires modifications.
136 env = env.copy()
137 def fix_lang(name):
138 if not is_english(name):
139 env[name] = 'en_US.UTF-8'
140 fix_lang('LANG')
141 fix_lang('LANGUAGE')
142 return env
143
144
szager@chromium.org12b07e72013-05-03 22:06:34 +0000145class NagTimer(object):
146 """
147 Triggers a callback when a time interval passes without an event being fired.
148
149 For example, the event could be receiving terminal output from a subprocess;
150 and the callback could print a warning to stderr that the subprocess appeared
151 to be hung.
152 """
153 def __init__(self, interval, cb):
154 self.interval = interval
155 self.cb = cb
156 self.timer = threading.Timer(self.interval, self.fn)
157 self.last_output = self.previous_last_output = 0
158
159 def start(self):
160 self.last_output = self.previous_last_output = time.time()
161 self.timer.start()
162
163 def event(self):
164 self.last_output = time.time()
165
166 def fn(self):
167 now = time.time()
168 if self.last_output == self.previous_last_output:
169 self.cb(now - self.previous_last_output)
170 # Use 0.1 fudge factor, just in case
171 # (self.last_output - now) is very close to zero.
172 sleep_time = (self.last_output - now - 0.1) % self.interval
173 self.previous_last_output = self.last_output
174 self.timer = threading.Timer(sleep_time + 0.1, self.fn)
175 self.timer.start()
176
177 def cancel(self):
178 self.timer.cancel()
179
180
maruel@google.comef77f9e2011-11-24 15:24:02 +0000181class Popen(subprocess.Popen):
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000182 """Wraps subprocess.Popen() with various workarounds.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000183
maruel@chromium.org421982f2011-04-01 17:38:06 +0000184 - Forces English output since it's easier to parse the stdout if it is always
185 in English.
186 - Sets shell=True on windows by default. You can override this by forcing
187 shell parameter to a value.
188 - Adds support for VOID to not buffer when not needed.
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000189 - Adds self.start property.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000190
maruel@chromium.org57bf78d2011-09-08 18:57:33 +0000191 Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate
192 exceptions generated by cygwin when it fails trying to emulate fork().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000193 """
torne@chromium.org434e7902015-09-15 09:57:01 +0000194 # subprocess.Popen.__init__() is not threadsafe; there is a race between
195 # creating the exec-error pipe for the child and setting it to CLOEXEC during
196 # which another thread can fork and cause the pipe to be inherited by its
197 # descendents, which will cause the current Popen to hang until all those
198 # descendents exit. Protect this with a lock so that only one fork/exec can
199 # happen at a time.
200 popen_lock = threading.Lock()
201
maruel@google.comef77f9e2011-11-24 15:24:02 +0000202 def __init__(self, args, **kwargs):
203 # Make sure we hack subprocess if necessary.
204 hack_subprocess()
205 add_kill()
maruel@chromium.org4860f052011-03-25 20:34:38 +0000206
maruel@google.comef77f9e2011-11-24 15:24:02 +0000207 env = get_english_env(kwargs.get('env'))
208 if env:
209 kwargs['env'] = env
210 if kwargs.get('shell') is None:
211 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for
212 # the executable, but shell=True makes subprocess on Linux fail when it's
213 # called with a list because it only tries to execute the first item in
214 # the list.
215 kwargs['shell'] = bool(sys.platform=='win32')
maruel@chromium.org4860f052011-03-25 20:34:38 +0000216
Raul Tambreb946b232019-03-26 14:48:46 +0000217 if isinstance(args, str) or (sys.version_info.major == 2 and
218 isinstance(args, unicode)):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000219 tmp_str = args
220 elif isinstance(args, (list, tuple)):
221 tmp_str = ' '.join(args)
222 else:
223 raise CalledProcessError(None, args, kwargs.get('cwd'), None, None)
224 if kwargs.get('cwd', None):
225 tmp_str += '; cwd=%s' % kwargs['cwd']
226 logging.debug(tmp_str)
maruel@chromium.org421982f2011-04-01 17:38:06 +0000227
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000228 self.stdout_cb = None
229 self.stderr_cb = None
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000230 self.stdin_is_void = False
231 self.stdout_is_void = False
232 self.stderr_is_void = False
szager@chromium.orge0558e62013-05-02 02:48:51 +0000233 self.cmd_str = tmp_str
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000234
235 if kwargs.get('stdin') is VOID:
236 kwargs['stdin'] = open(os.devnull, 'r')
237 self.stdin_is_void = True
238
239 for stream in ('stdout', 'stderr'):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000240 if kwargs.get(stream) in (VOID, os.devnull):
maruel@google.comef77f9e2011-11-24 15:24:02 +0000241 kwargs[stream] = open(os.devnull, 'w')
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000242 setattr(self, stream + '_is_void', True)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000243 if callable(kwargs.get(stream)):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000244 setattr(self, stream + '_cb', kwargs[stream])
245 kwargs[stream] = PIPE
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000246
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000247 self.start = time.time()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000248 self.timeout = None
szager@chromium.orge0558e62013-05-02 02:48:51 +0000249 self.nag_timer = None
szager@chromium.org12b07e72013-05-03 22:06:34 +0000250 self.nag_max = None
maruel@chromium.orga8e81632011-12-01 00:35:24 +0000251 self.shell = kwargs.get('shell', None)
maruel@chromium.org14e37ad2011-11-30 20:26:16 +0000252 # Silence pylint on MacOSX
253 self.returncode = None
maruel@chromium.orga8e81632011-12-01 00:35:24 +0000254
maruel@google.comef77f9e2011-11-24 15:24:02 +0000255 try:
torne@chromium.org434e7902015-09-15 09:57:01 +0000256 with self.popen_lock:
257 super(Popen, self).__init__(args, **kwargs)
Raul Tambreb946b232019-03-26 14:48:46 +0000258 except OSError as e:
maruel@google.comef77f9e2011-11-24 15:24:02 +0000259 if e.errno == errno.EAGAIN and sys.platform == 'cygwin':
260 # Convert fork() emulation failure into a CygwinRebaseError().
261 raise CygwinRebaseError(
262 e.errno,
263 args,
264 kwargs.get('cwd'),
265 None,
266 'Visit '
267 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure '
268 'to learn how to fix this error; you need to rebase your cygwin '
269 'dlls')
luqui@chromium.org7f627a92014-03-28 00:57:44 +0000270 # Popen() can throw OSError when cwd or args[0] doesn't exist.
pgervais@chromium.orgfb653b62014-04-29 17:29:18 +0000271 raise OSError('Execution failed with error: %s.\n'
272 'Check that %s or %s exist and have execution permission.'
273 % (str(e), kwargs.get('cwd'), args[0]))
maruel@chromium.org4860f052011-03-25 20:34:38 +0000274
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800275 def _tee_threads(self, input): # pylint: disable=redefined-builtin
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000276 """Does I/O for a process's pipes using threads.
277
278 It's the simplest and slowest implementation. Expect very slow behavior.
279
280 If there is a callback and it doesn't keep up with the calls, the timeout
281 effectiveness will be delayed accordingly.
282 """
283 # Queue of either of <threadname> when done or (<threadname>, data). In
284 # theory we would like to limit to ~64kb items to not cause large memory
285 # usage when the callback blocks. It is not done because it slows down
286 # processing on OSX10.6 by a factor of 2x, making it even slower than
287 # Windows! Revisit this decision if it becomes a problem, e.g. crash
288 # because of memory exhaustion.
289 queue = Queue.Queue()
290 done = threading.Event()
szager@chromium.org12b07e72013-05-03 22:06:34 +0000291 nag = None
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000292
293 def write_stdin():
294 try:
Raul Tambreb946b232019-03-26 14:48:46 +0000295 stdin_io = io.BytesIO(input)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000296 while True:
297 data = stdin_io.read(1024)
298 if data:
299 self.stdin.write(data)
300 else:
301 self.stdin.close()
302 break
303 finally:
304 queue.put('stdin')
305
306 def _queue_pipe_read(pipe, name):
307 """Queues characters read from a pipe into a queue."""
308 try:
309 while True:
310 data = pipe.read(1)
311 if not data:
312 break
szager@chromium.org12b07e72013-05-03 22:06:34 +0000313 if nag:
314 nag.event()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000315 queue.put((name, data))
316 finally:
317 queue.put(name)
318
319 def timeout_fn():
320 try:
321 done.wait(self.timeout)
322 finally:
323 queue.put('timeout')
324
325 def wait_fn():
326 try:
327 self.wait()
328 finally:
329 queue.put('wait')
330
331 # Starts up to 5 threads:
332 # Wait for the process to quit
333 # Read stdout
334 # Read stderr
335 # Write stdin
336 # Timeout
337 threads = {
338 'wait': threading.Thread(target=wait_fn),
339 }
340 if self.timeout is not None:
341 threads['timeout'] = threading.Thread(target=timeout_fn)
342 if self.stdout_cb:
343 threads['stdout'] = threading.Thread(
344 target=_queue_pipe_read, args=(self.stdout, 'stdout'))
345 if self.stderr_cb:
346 threads['stderr'] = threading.Thread(
347 target=_queue_pipe_read, args=(self.stderr, 'stderr'))
348 if input:
349 threads['stdin'] = threading.Thread(target=write_stdin)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000350 elif self.stdin:
351 # Pipe but no input, make sure it's closed.
352 self.stdin.close()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000353 for t in threads.itervalues():
354 t.start()
355
szager@chromium.orge0558e62013-05-02 02:48:51 +0000356 if self.nag_timer:
szager@chromium.org12b07e72013-05-03 22:06:34 +0000357 def _nag_cb(elapsed):
358 logging.warn(' No output for %.0f seconds from command:' % elapsed)
359 logging.warn(' %s' % self.cmd_str)
360 if (self.nag_max and
361 int('%.0f' % (elapsed / self.nag_timer)) >= self.nag_max):
362 queue.put('timeout')
363 done.set() # Must do this so that timeout thread stops waiting.
364 nag = NagTimer(self.nag_timer, _nag_cb)
365 nag.start()
szager@chromium.orge0558e62013-05-02 02:48:51 +0000366
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000367 timed_out = False
368 try:
369 # This thread needs to be optimized for speed.
370 while threads:
371 item = queue.get()
maruel@chromium.orgcd8d8e12012-10-03 17:16:25 +0000372 if item[0] == 'stdout':
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000373 self.stdout_cb(item[1])
maruel@chromium.orgcd8d8e12012-10-03 17:16:25 +0000374 elif item[0] == 'stderr':
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000375 self.stderr_cb(item[1])
376 else:
377 # A thread terminated.
szager@chromium.org12b07e72013-05-03 22:06:34 +0000378 if item in threads:
379 threads[item].join()
380 del threads[item]
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000381 if item == 'wait':
382 # Terminate the timeout thread if necessary.
383 done.set()
384 elif item == 'timeout' and not timed_out and self.poll() is None:
szager@chromium.org12b07e72013-05-03 22:06:34 +0000385 logging.debug('Timed out after %.0fs: killing' % (
386 time.time() - self.start))
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000387 self.kill()
388 timed_out = True
389 finally:
390 # Stop the threads.
391 done.set()
szager@chromium.org12b07e72013-05-03 22:06:34 +0000392 if nag:
393 nag.cancel()
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000394 if 'wait' in threads:
395 # Accelerate things, otherwise it would hang until the child process is
396 # done.
397 logging.debug('Killing child because of an exception')
398 self.kill()
399 # Join threads.
400 for thread in threads.itervalues():
401 thread.join()
402 if timed_out:
403 self.returncode = TIMED_OUT
404
Quinten Yearsleyb2cc4a92016-12-15 13:53:26 -0800405 # pylint: disable=arguments-differ,W0622
szager@chromium.org12b07e72013-05-03 22:06:34 +0000406 def communicate(self, input=None, timeout=None, nag_timer=None,
407 nag_max=None):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000408 """Adds timeout and callbacks support.
409
410 Returns (stdout, stderr) like subprocess.Popen().communicate().
411
412 - 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.org94c712f2011-12-01 15:04:57 +0000416 """
417 self.timeout = timeout
szager@chromium.orge0558e62013-05-02 02:48:51 +0000418 self.nag_timer = nag_timer
szager@chromium.org12b07e72013-05-03 22:06:34 +0000419 self.nag_max = nag_max
szager@chromium.orge0558e62013-05-02 02:48:51 +0000420 if (not self.timeout and not self.nag_timer and
421 not self.stdout_cb and not self.stderr_cb):
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000422 return super(Popen, self).communicate(input)
423
424 if self.timeout and self.shell:
425 raise TypeError(
426 'Using timeout and shell simultaneously will cause a process leak '
427 'since the shell will be killed instead of the child process.')
428
429 stdout = None
430 stderr = None
431 # Convert to a lambda to workaround python's deadlock.
432 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000433 # When the pipe fills up, it would deadlock this process.
434 if self.stdout and not self.stdout_cb and not self.stdout_is_void:
435 stdout = []
436 self.stdout_cb = stdout.append
437 if self.stderr and not self.stderr_cb and not self.stderr_is_void:
438 stderr = []
439 self.stderr_cb = stderr.append
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000440 self._tee_threads(input)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000441 if stdout is not None:
442 stdout = ''.join(stdout)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000443 if stderr is not None:
444 stderr = ''.join(stderr)
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000445 return (stdout, stderr)
446
maruel@chromium.org4860f052011-03-25 20:34:38 +0000447
szager@chromium.org12b07e72013-05-03 22:06:34 +0000448def communicate(args, timeout=None, nag_timer=None, nag_max=None, **kwargs):
maruel@chromium.orgdd9837f2011-11-30 01:55:22 +0000449 """Wraps subprocess.Popen().communicate() and add timeout support.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000450
maruel@chromium.org421982f2011-04-01 17:38:06 +0000451 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000452
maruel@chromium.org1d9f6292011-04-07 14:15:36 +0000453 - The process will be killed after |timeout| seconds and returncode set to
454 TIMED_OUT.
szager@chromium.orge0558e62013-05-02 02:48:51 +0000455 - If the subprocess runs for |nag_timer| seconds without producing terminal
456 output, print a warning to stderr.
maruel@chromium.org421982f2011-04-01 17:38:06 +0000457 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000458 """
459 stdin = kwargs.pop('stdin', None)
460 if stdin is not None:
Raul Tambreb946b232019-03-26 14:48:46 +0000461 if isinstance(stdin, str) or (sys.version_info.major == 2 and
462 isinstance(stdin, unicode)):
maruel@chromium.org0d5ef242011-04-18 13:52:58 +0000463 # When stdin is passed as an argument, use it as the actual input data and
464 # set the Popen() parameter accordingly.
465 kwargs['stdin'] = PIPE
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000466 else:
467 kwargs['stdin'] = stdin
468 stdin = None
maruel@chromium.org4860f052011-03-25 20:34:38 +0000469
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000470 proc = Popen(args, **kwargs)
maruel@chromium.org740a6c02011-12-05 23:46:44 +0000471 if stdin:
szager@chromium.orge0558e62013-05-02 02:48:51 +0000472 return proc.communicate(stdin, timeout, nag_timer), proc.returncode
maruel@chromium.org94c712f2011-12-01 15:04:57 +0000473 else:
szager@chromium.orge0558e62013-05-02 02:48:51 +0000474 return proc.communicate(None, timeout, nag_timer), proc.returncode
maruel@chromium.org4860f052011-03-25 20:34:38 +0000475
476
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000477def call(args, **kwargs):
478 """Emulates subprocess.call().
479
480 Automatically convert stdout=PIPE or stderr=PIPE to VOID.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000481 In no case they can be returned since no code path raises
482 subprocess2.CalledProcessError.
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000483 """
484 if kwargs.get('stdout') == PIPE:
485 kwargs['stdout'] = VOID
486 if kwargs.get('stderr') == PIPE:
487 kwargs['stderr'] = VOID
488 return communicate(args, **kwargs)[1]
489
490
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000491def check_call_out(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000492 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000493
maruel@chromium.org421982f2011-04-01 17:38:06 +0000494 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000495 """
maruel@chromium.org1f063db2011-04-18 19:04:52 +0000496 out, returncode = communicate(args, **kwargs)
maruel@chromium.org4860f052011-03-25 20:34:38 +0000497 if returncode:
498 raise CalledProcessError(
499 returncode, args, kwargs.get('cwd'), out[0], out[1])
500 return out
501
502
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000503def check_call(args, **kwargs):
504 """Emulate subprocess.check_call()."""
505 check_call_out(args, **kwargs)
506 return 0
507
508
maruel@chromium.org4860f052011-03-25 20:34:38 +0000509def capture(args, **kwargs):
510 """Captures stdout of a process call and returns it.
511
maruel@chromium.org421982f2011-04-01 17:38:06 +0000512 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000513
maruel@chromium.org421982f2011-04-01 17:38:06 +0000514 - Discards returncode.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000515 - Blocks stdin by default if not specified since no output will be visible.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000516 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000517 kwargs.setdefault('stdin', VOID)
518
519 # Like check_output, deny the caller from using stdout arg.
520 return communicate(args, stdout=PIPE, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000521
522
523def check_output(args, **kwargs):
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000524 """Emulates subprocess.check_output().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000525
maruel@chromium.org0bcd1d32011-04-26 15:55:49 +0000526 Captures stdout of a process call and returns stdout only.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000527
maruel@chromium.org421982f2011-04-01 17:38:06 +0000528 - Throws if return code is not 0.
529 - Works even prior to python 2.7.
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000530 - Blocks stdin by default if not specified since no output will be visible.
531 - As per doc, "The stdout argument is not allowed as it is used internally."
maruel@chromium.org4860f052011-03-25 20:34:38 +0000532 """
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000533 kwargs.setdefault('stdin', VOID)
maruel@chromium.orgdb59bfc2011-11-30 14:03:14 +0000534 if 'stdout' in kwargs:
pgervais@chromium.org022d06e2014-04-29 17:08:12 +0000535 raise ValueError('stdout argument not allowed, it would be overridden.')
maruel@chromium.org87e6d332011-09-09 19:01:28 +0000536 return check_call_out(args, stdout=PIPE, **kwargs)[0]