maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 1 | # 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 | |
| 7 | In theory you shouldn't need anything else in subprocess, or this module failed. |
| 8 | """ |
| 9 | |
maruel@chromium.org | 45d8db0 | 2011-03-31 20:43:56 +0000 | [diff] [blame] | 10 | from __future__ import with_statement |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 11 | import logging |
| 12 | import os |
| 13 | import subprocess |
| 14 | import sys |
| 15 | import tempfile |
| 16 | import time |
| 17 | import threading |
| 18 | |
| 19 | # Constants forwarded from subprocess. |
| 20 | PIPE = subprocess.PIPE |
| 21 | STDOUT = subprocess.STDOUT |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 22 | # Sends stdout or stderr to os.devnull. |
| 23 | VOID = '/dev/null' |
| 24 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 25 | |
| 26 | # Globals. |
| 27 | # Set to True if you somehow need to disable this hack. |
| 28 | SUBPROCESS_CLEANUP_HACKED = False |
| 29 | |
| 30 | |
| 31 | class 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.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 47 | ## Utility functions |
| 48 | |
| 49 | |
| 50 | def 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 | |
| 61 | def 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 | |
| 77 | def 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.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 88 | def 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 | |
| 101 | def 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 | |
| 126 | def Popen(args, **kwargs): |
maruel@chromium.org | 58ef297 | 2011-04-01 21:00:11 +0000 | [diff] [blame] | 127 | """Wraps subprocess.Popen(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 128 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 129 | Returns a subprocess.Popen object. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 130 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 131 | - 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.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 136 | |
maruel@chromium.org | 58ef297 | 2011-04-01 21:00:11 +0000 | [diff] [blame] | 137 | Note: Popen() can throw OSError when cwd or args[0] doesn't exist. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 138 | """ |
| 139 | # Make sure we hack subprocess if necessary. |
| 140 | hack_subprocess() |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 141 | add_kill() |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 142 | |
| 143 | env = get_english_env(kwargs.get('env')) |
| 144 | if env: |
| 145 | kwargs['env'] = env |
| 146 | |
| 147 | if not kwargs.get('shell') is None: |
| 148 | # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for the |
| 149 | # executable, but shell=True makes subprocess on Linux fail when it's called |
| 150 | # with a list because it only tries to execute the first item in the list. |
| 151 | kwargs['shell'] = (sys.platform=='win32') |
| 152 | |
| 153 | tmp_str = ' '.join(args) |
| 154 | if kwargs.get('cwd', None): |
| 155 | tmp_str += '; cwd=%s' % kwargs['cwd'] |
| 156 | logging.debug(tmp_str) |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 157 | |
| 158 | # Replaces VOID with handle to /dev/null. |
| 159 | if kwargs.get('stdout') in (VOID, os.devnull): |
| 160 | kwargs['stdout'] = open(os.devnull, 'w') |
| 161 | if kwargs.get('stderr') in (VOID, os.devnull): |
| 162 | kwargs['stderr'] = open(os.devnull, 'w') |
maruel@chromium.org | 58ef297 | 2011-04-01 21:00:11 +0000 | [diff] [blame] | 163 | return subprocess.Popen(args, **kwargs) |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 164 | |
| 165 | |
| 166 | def call(args, timeout=None, **kwargs): |
| 167 | """Wraps subprocess.Popen().communicate(). |
| 168 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 169 | Returns ((stdout, stderr), returncode). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 170 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 171 | - The process will be kill with error code -9 after |timeout| seconds if set. |
| 172 | - Automatically passes stdin content as input so do not specify stdin=PIPE. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 173 | """ |
| 174 | stdin = kwargs.pop('stdin', None) |
| 175 | if stdin is not None: |
| 176 | assert stdin != PIPE |
| 177 | # When stdin is passed as an argument, use it as the actual input data and |
| 178 | # set the Popen() parameter accordingly. |
| 179 | kwargs['stdin'] = PIPE |
| 180 | |
| 181 | if not timeout: |
| 182 | # Normal workflow. |
| 183 | proc = Popen(args, **kwargs) |
| 184 | if stdin is not None: |
| 185 | out = proc.communicate(stdin) |
| 186 | else: |
| 187 | out = proc.communicate() |
| 188 | else: |
| 189 | # Create a temporary file to workaround python's deadlock. |
| 190 | # http://docs.python.org/library/subprocess.html#subprocess.Popen.wait |
| 191 | # When the pipe fills up, it will deadlock this process. Using a real file |
| 192 | # works around that issue. |
| 193 | with tempfile.TemporaryFile() as buff: |
| 194 | start = time.time() |
| 195 | kwargs['stdout'] = buff |
| 196 | proc = Popen(args, **kwargs) |
| 197 | if stdin is not None: |
| 198 | proc.stdin.write(stdin) |
| 199 | while proc.returncode is None: |
| 200 | proc.poll() |
| 201 | if timeout and (time.time() - start) > timeout: |
| 202 | proc.kill() |
| 203 | proc.wait() |
| 204 | # It's -9 on linux and 1 on Windows. Standardize to -9. |
| 205 | # Do not throw an exception here, the user must use |
| 206 | # check_call(timeout=60) and check for e.returncode == -9 instead. |
| 207 | # or look at call()[1] == -9. |
| 208 | proc.returncode = -9 |
| 209 | time.sleep(0.001) |
| 210 | # Now that the process died, reset the cursor and read the file. |
| 211 | buff.seek(0) |
| 212 | out = [buff.read(), None] |
| 213 | return out, proc.returncode |
| 214 | |
| 215 | |
| 216 | def check_call(args, **kwargs): |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 217 | """Improved version of subprocess.check_call(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 218 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 219 | Returns (stdout, stderr), unlike subprocess.check_call(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 220 | """ |
| 221 | out, returncode = call(args, **kwargs) |
| 222 | if returncode: |
| 223 | raise CalledProcessError( |
| 224 | returncode, args, kwargs.get('cwd'), out[0], out[1]) |
| 225 | return out |
| 226 | |
| 227 | |
| 228 | def capture(args, **kwargs): |
| 229 | """Captures stdout of a process call and returns it. |
| 230 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 231 | Returns stdout. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 232 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 233 | - Discards returncode. |
| 234 | - Discards stderr. By default sets stderr=STDOUT. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 235 | """ |
| 236 | if kwargs.get('stderr') is None: |
| 237 | kwargs['stderr'] = STDOUT |
| 238 | return call(args, stdout=PIPE, **kwargs)[0][0] |
| 239 | |
| 240 | |
| 241 | def check_output(args, **kwargs): |
| 242 | """Captures stdout of a process call and returns it. |
| 243 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 244 | Returns stdout. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 245 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 246 | - Discards stderr. By default sets stderr=STDOUT. |
| 247 | - Throws if return code is not 0. |
| 248 | - Works even prior to python 2.7. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 249 | """ |
| 250 | if kwargs.get('stderr') is None: |
| 251 | kwargs['stderr'] = STDOUT |
| 252 | return check_call(args, stdout=PIPE, **kwargs)[0] |