blob: acba499ae13d38fab3236ea61c0f518cb902826e [file] [log] [blame]
maruel@chromium.org4860f052011-03-25 20:34:38 +00001# coding=utf8
2# Copyright (c) 2011 The Chromium Authors. All rights reserved.
3# 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.org45d8db02011-03-31 20:43:56 +000010from __future__ import with_statement
maruel@chromium.org4860f052011-03-25 20:34:38 +000011import logging
12import os
13import subprocess
14import sys
15import tempfile
16import time
17import threading
18
19# Constants forwarded from subprocess.
20PIPE = subprocess.PIPE
21STDOUT = subprocess.STDOUT
maruel@chromium.org421982f2011-04-01 17:38:06 +000022# Sends stdout or stderr to os.devnull.
23VOID = '/dev/null'
24
maruel@chromium.org4860f052011-03-25 20:34:38 +000025
26# Globals.
27# Set to True if you somehow need to disable this hack.
28SUBPROCESS_CLEANUP_HACKED = False
29
30
31class CalledProcessError(subprocess.CalledProcessError):
32 """Augment the standard exception with more data."""
33 def __init__(self, returncode, cmd, cwd, stdout, stderr):
34 super(CalledProcessError, self).__init__(returncode, cmd)
35 self.stdout = stdout
36 self.stderr = stderr
37 self.cwd = cwd
38
39 def __str__(self):
40 out = 'Command %s returned non-zero exit status %s' % (
41 ' '.join(self.cmd), self.returncode)
42 if self.cwd:
43 out += ' in ' + self.cwd
44 return '\n'.join(filter(None, (out, self.stdout, self.stderr)))
45
46
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000047## Utility functions
48
49
50def kill_pid(pid):
51 """Kills a process by its process id."""
52 try:
53 # Unable to import 'module'
54 # pylint: disable=F0401
55 import signal
56 return os.kill(pid, signal.SIGKILL)
57 except ImportError:
58 pass
59
60
61def kill_win(process):
62 """Kills a process with its windows handle.
63
64 Has no effect on other platforms.
65 """
66 try:
67 # Unable to import 'module'
68 # pylint: disable=F0401
69 import win32process
70 # Access to a protected member _handle of a client class
71 # pylint: disable=W0212
72 return win32process.TerminateProcess(process._handle, -1)
73 except ImportError:
74 pass
75
76
77def add_kill():
78 """Adds kill() method to subprocess.Popen for python <2.6"""
79 if hasattr(subprocess.Popen, 'kill'):
80 return
81
82 if sys.platform == 'win32':
83 subprocess.Popen.kill = kill_win
84 else:
85 subprocess.Popen.kill = lambda process: kill_pid(process.pid)
86
87
maruel@chromium.org4860f052011-03-25 20:34:38 +000088def hack_subprocess():
89 """subprocess functions may throw exceptions when used in multiple threads.
90
91 See http://bugs.python.org/issue1731717 for more information.
92 """
93 global SUBPROCESS_CLEANUP_HACKED
94 if not SUBPROCESS_CLEANUP_HACKED and threading.activeCount() != 1:
95 # Only hack if there is ever multiple threads.
96 # There is no point to leak with only one thread.
97 subprocess._cleanup = lambda: None
98 SUBPROCESS_CLEANUP_HACKED = True
99
100
101def get_english_env(env):
102 """Forces LANG and/or LANGUAGE to be English.
103
104 Forces encoding to utf-8 for subprocesses.
105
106 Returns None if it is unnecessary.
107 """
108 env = env or os.environ
109
110 # Test if it is necessary at all.
111 is_english = lambda name: env.get(name, 'en').startswith('en')
112
113 if is_english('LANG') and is_english('LANGUAGE'):
114 return None
115
116 # Requires modifications.
117 env = env.copy()
118 def fix_lang(name):
119 if not is_english(name):
120 env[name] = 'en_US.UTF-8'
121 fix_lang('LANG')
122 fix_lang('LANGUAGE')
123 return env
124
125
126def Popen(args, **kwargs):
maruel@chromium.org58ef2972011-04-01 21:00:11 +0000127 """Wraps subprocess.Popen().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000128
maruel@chromium.org421982f2011-04-01 17:38:06 +0000129 Returns a subprocess.Popen object.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000130
maruel@chromium.org421982f2011-04-01 17:38:06 +0000131 - Forces English output since it's easier to parse the stdout if it is always
132 in English.
133 - Sets shell=True on windows by default. You can override this by forcing
134 shell parameter to a value.
135 - Adds support for VOID to not buffer when not needed.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000136
maruel@chromium.org58ef2972011-04-01 21:00:11 +0000137 Note: Popen() can throw OSError when cwd or args[0] doesn't exist.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000138 """
139 # Make sure we hack subprocess if necessary.
140 hack_subprocess()
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +0000141 add_kill()
maruel@chromium.org4860f052011-03-25 20:34:38 +0000142
143 env = get_english_env(kwargs.get('env'))
144 if env:
145 kwargs['env'] = env
maruel@chromium.orgf08b09c2011-04-06 13:14:27 +0000146 if kwargs.get('shell') is None:
maruel@chromium.org4860f052011-03-25 20:34:38 +0000147 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for the
148 # executable, but shell=True makes subprocess on Linux fail when it's called
149 # with a list because it only tries to execute the first item in the list.
maruel@chromium.orgf08b09c2011-04-06 13:14:27 +0000150 kwargs['shell'] = bool(sys.platform=='win32')
maruel@chromium.org4860f052011-03-25 20:34:38 +0000151
152 tmp_str = ' '.join(args)
153 if kwargs.get('cwd', None):
154 tmp_str += '; cwd=%s' % kwargs['cwd']
155 logging.debug(tmp_str)
maruel@chromium.org421982f2011-04-01 17:38:06 +0000156
157 # Replaces VOID with handle to /dev/null.
158 if kwargs.get('stdout') in (VOID, os.devnull):
159 kwargs['stdout'] = open(os.devnull, 'w')
160 if kwargs.get('stderr') in (VOID, os.devnull):
161 kwargs['stderr'] = open(os.devnull, 'w')
maruel@chromium.org58ef2972011-04-01 21:00:11 +0000162 return subprocess.Popen(args, **kwargs)
maruel@chromium.org4860f052011-03-25 20:34:38 +0000163
164
165def call(args, timeout=None, **kwargs):
166 """Wraps subprocess.Popen().communicate().
167
maruel@chromium.org421982f2011-04-01 17:38:06 +0000168 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000169
maruel@chromium.org421982f2011-04-01 17:38:06 +0000170 - The process will be kill with error code -9 after |timeout| seconds if set.
171 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000172 """
173 stdin = kwargs.pop('stdin', None)
174 if stdin is not None:
175 assert stdin != PIPE
176 # When stdin is passed as an argument, use it as the actual input data and
177 # set the Popen() parameter accordingly.
178 kwargs['stdin'] = PIPE
179
180 if not timeout:
181 # Normal workflow.
182 proc = Popen(args, **kwargs)
183 if stdin is not None:
184 out = proc.communicate(stdin)
185 else:
186 out = proc.communicate()
187 else:
188 # Create a temporary file to workaround python's deadlock.
189 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
190 # When the pipe fills up, it will deadlock this process. Using a real file
191 # works around that issue.
192 with tempfile.TemporaryFile() as buff:
193 start = time.time()
194 kwargs['stdout'] = buff
195 proc = Popen(args, **kwargs)
196 if stdin is not None:
197 proc.stdin.write(stdin)
198 while proc.returncode is None:
199 proc.poll()
200 if timeout and (time.time() - start) > timeout:
201 proc.kill()
202 proc.wait()
203 # It's -9 on linux and 1 on Windows. Standardize to -9.
204 # Do not throw an exception here, the user must use
205 # check_call(timeout=60) and check for e.returncode == -9 instead.
206 # or look at call()[1] == -9.
207 proc.returncode = -9
208 time.sleep(0.001)
209 # Now that the process died, reset the cursor and read the file.
210 buff.seek(0)
211 out = [buff.read(), None]
212 return out, proc.returncode
213
214
215def check_call(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000216 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000217
maruel@chromium.org421982f2011-04-01 17:38:06 +0000218 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000219 """
220 out, returncode = call(args, **kwargs)
221 if returncode:
222 raise CalledProcessError(
223 returncode, args, kwargs.get('cwd'), out[0], out[1])
224 return out
225
226
227def capture(args, **kwargs):
228 """Captures stdout of a process call and returns it.
229
maruel@chromium.org421982f2011-04-01 17:38:06 +0000230 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000231
maruel@chromium.org421982f2011-04-01 17:38:06 +0000232 - Discards returncode.
233 - Discards stderr. By default sets stderr=STDOUT.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000234 """
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000235 if kwargs.get('stdout') is None:
236 kwargs['stdout'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000237 if kwargs.get('stderr') is None:
238 kwargs['stderr'] = STDOUT
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000239 return call(args, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000240
241
242def check_output(args, **kwargs):
243 """Captures stdout of a process call and returns it.
244
maruel@chromium.org421982f2011-04-01 17:38:06 +0000245 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000246
maruel@chromium.org421982f2011-04-01 17:38:06 +0000247 - Discards stderr. By default sets stderr=STDOUT.
248 - Throws if return code is not 0.
249 - Works even prior to python 2.7.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000250 """
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000251 if kwargs.get('stdout') is None:
252 kwargs['stdout'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000253 if kwargs.get('stderr') is None:
254 kwargs['stderr'] = STDOUT
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000255 return check_call(args, **kwargs)[0]