blob: 77fda58d291c2f552f5fb6793de0ebc6a36aa836 [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'
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +000054 # pylint: disable=E1101,F0401
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +000055 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 """
maruel@chromium.orgc98c0c52011-04-06 13:39:43 +0000108 if sys.platform == 'win32':
109 return None
maruel@chromium.org4860f052011-03-25 20:34:38 +0000110 env = env or os.environ
111
112 # Test if it is necessary at all.
113 is_english = lambda name: env.get(name, 'en').startswith('en')
114
115 if is_english('LANG') and is_english('LANGUAGE'):
116 return None
117
118 # Requires modifications.
119 env = env.copy()
120 def fix_lang(name):
121 if not is_english(name):
122 env[name] = 'en_US.UTF-8'
123 fix_lang('LANG')
124 fix_lang('LANGUAGE')
125 return env
126
127
128def Popen(args, **kwargs):
maruel@chromium.org58ef2972011-04-01 21:00:11 +0000129 """Wraps subprocess.Popen().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000130
maruel@chromium.org421982f2011-04-01 17:38:06 +0000131 Returns a subprocess.Popen object.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000132
maruel@chromium.org421982f2011-04-01 17:38:06 +0000133 - Forces English output since it's easier to parse the stdout if it is always
134 in English.
135 - Sets shell=True on windows by default. You can override this by forcing
136 shell parameter to a value.
137 - Adds support for VOID to not buffer when not needed.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000138
maruel@chromium.org58ef2972011-04-01 21:00:11 +0000139 Note: Popen() can throw OSError when cwd or args[0] doesn't exist.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000140 """
141 # Make sure we hack subprocess if necessary.
142 hack_subprocess()
maruel@chromium.orgfb3d3242011-04-01 14:03:08 +0000143 add_kill()
maruel@chromium.org4860f052011-03-25 20:34:38 +0000144
145 env = get_english_env(kwargs.get('env'))
146 if env:
147 kwargs['env'] = env
maruel@chromium.orgf08b09c2011-04-06 13:14:27 +0000148 if kwargs.get('shell') is None:
maruel@chromium.org4860f052011-03-25 20:34:38 +0000149 # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for the
150 # executable, but shell=True makes subprocess on Linux fail when it's called
151 # with a list because it only tries to execute the first item in the list.
maruel@chromium.orgf08b09c2011-04-06 13:14:27 +0000152 kwargs['shell'] = bool(sys.platform=='win32')
maruel@chromium.org4860f052011-03-25 20:34:38 +0000153
154 tmp_str = ' '.join(args)
155 if kwargs.get('cwd', None):
156 tmp_str += '; cwd=%s' % kwargs['cwd']
157 logging.debug(tmp_str)
maruel@chromium.org421982f2011-04-01 17:38:06 +0000158
159 # Replaces VOID with handle to /dev/null.
160 if kwargs.get('stdout') in (VOID, os.devnull):
161 kwargs['stdout'] = open(os.devnull, 'w')
162 if kwargs.get('stderr') in (VOID, os.devnull):
163 kwargs['stderr'] = open(os.devnull, 'w')
maruel@chromium.org58ef2972011-04-01 21:00:11 +0000164 return subprocess.Popen(args, **kwargs)
maruel@chromium.org4860f052011-03-25 20:34:38 +0000165
166
167def call(args, timeout=None, **kwargs):
168 """Wraps subprocess.Popen().communicate().
169
maruel@chromium.org421982f2011-04-01 17:38:06 +0000170 Returns ((stdout, stderr), returncode).
maruel@chromium.org4860f052011-03-25 20:34:38 +0000171
maruel@chromium.org421982f2011-04-01 17:38:06 +0000172 - The process will be kill with error code -9 after |timeout| seconds if set.
173 - Automatically passes stdin content as input so do not specify stdin=PIPE.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000174 """
175 stdin = kwargs.pop('stdin', None)
176 if stdin is not None:
177 assert stdin != PIPE
178 # When stdin is passed as an argument, use it as the actual input data and
179 # set the Popen() parameter accordingly.
180 kwargs['stdin'] = PIPE
181
182 if not timeout:
183 # Normal workflow.
184 proc = Popen(args, **kwargs)
185 if stdin is not None:
186 out = proc.communicate(stdin)
187 else:
188 out = proc.communicate()
189 else:
190 # Create a temporary file to workaround python's deadlock.
191 # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait
192 # When the pipe fills up, it will deadlock this process. Using a real file
193 # works around that issue.
194 with tempfile.TemporaryFile() as buff:
195 start = time.time()
196 kwargs['stdout'] = buff
197 proc = Popen(args, **kwargs)
198 if stdin is not None:
199 proc.stdin.write(stdin)
200 while proc.returncode is None:
201 proc.poll()
202 if timeout and (time.time() - start) > timeout:
203 proc.kill()
204 proc.wait()
205 # It's -9 on linux and 1 on Windows. Standardize to -9.
206 # Do not throw an exception here, the user must use
207 # check_call(timeout=60) and check for e.returncode == -9 instead.
208 # or look at call()[1] == -9.
209 proc.returncode = -9
210 time.sleep(0.001)
211 # Now that the process died, reset the cursor and read the file.
212 buff.seek(0)
213 out = [buff.read(), None]
214 return out, proc.returncode
215
216
217def check_call(args, **kwargs):
maruel@chromium.org421982f2011-04-01 17:38:06 +0000218 """Improved version of subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000219
maruel@chromium.org421982f2011-04-01 17:38:06 +0000220 Returns (stdout, stderr), unlike subprocess.check_call().
maruel@chromium.org4860f052011-03-25 20:34:38 +0000221 """
222 out, returncode = call(args, **kwargs)
223 if returncode:
224 raise CalledProcessError(
225 returncode, args, kwargs.get('cwd'), out[0], out[1])
226 return out
227
228
229def capture(args, **kwargs):
230 """Captures stdout of a process call and returns it.
231
maruel@chromium.org421982f2011-04-01 17:38:06 +0000232 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000233
maruel@chromium.org421982f2011-04-01 17:38:06 +0000234 - Discards returncode.
235 - Discards stderr. By default sets stderr=STDOUT.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000236 """
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000237 if kwargs.get('stdout') is None:
238 kwargs['stdout'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000239 if kwargs.get('stderr') is None:
240 kwargs['stderr'] = STDOUT
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000241 return call(args, **kwargs)[0][0]
maruel@chromium.org4860f052011-03-25 20:34:38 +0000242
243
244def check_output(args, **kwargs):
245 """Captures stdout of a process call and returns it.
246
maruel@chromium.org421982f2011-04-01 17:38:06 +0000247 Returns stdout.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000248
maruel@chromium.org421982f2011-04-01 17:38:06 +0000249 - Discards stderr. By default sets stderr=STDOUT.
250 - Throws if return code is not 0.
251 - Works even prior to python 2.7.
maruel@chromium.org4860f052011-03-25 20:34:38 +0000252 """
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000253 if kwargs.get('stdout') is None:
254 kwargs['stdout'] = PIPE
maruel@chromium.org4860f052011-03-25 20:34:38 +0000255 if kwargs.get('stderr') is None:
256 kwargs['stderr'] = STDOUT
maruel@chromium.orgeba40222011-04-05 14:52:48 +0000257 return check_call(args, **kwargs)[0]