Raul Tambre | a04028c | 2019-05-13 17:23:36 +0000 | [diff] [blame] | 1 | # coding=utf-8 |
maruel@chromium.org | 4f6852c | 2012-04-20 20:39:20 +0000 | [diff] [blame] | 2 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 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 | |
John Budorick | 9875e18 | 2018-12-05 22:57:31 +0000 | [diff] [blame] | 10 | import codecs |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 11 | import errno |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 12 | import logging |
| 13 | import os |
| 14 | import subprocess |
| 15 | import sys |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 16 | import threading |
| 17 | |
Aaron Gable | ac9b0f3 | 2019-04-18 17:38:37 +0000 | [diff] [blame] | 18 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 19 | # Constants forwarded from subprocess. |
| 20 | PIPE = subprocess.PIPE |
| 21 | STDOUT = subprocess.STDOUT |
Gavin Mak | 512f3cb | 2023-09-05 18:02:24 +0000 | [diff] [blame] | 22 | DEVNULL = subprocess.DEVNULL |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 23 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 24 | |
| 25 | class CalledProcessError(subprocess.CalledProcessError): |
| 26 | """Augment the standard exception with more data.""" |
| 27 | def __init__(self, returncode, cmd, cwd, stdout, stderr): |
tandrii@chromium.org | c15fe57 | 2014-09-19 11:51:43 +0000 | [diff] [blame] | 28 | super(CalledProcessError, self).__init__(returncode, cmd, output=stdout) |
| 29 | self.stdout = self.output # for backward compatibility. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 30 | self.stderr = stderr |
| 31 | self.cwd = cwd |
| 32 | |
| 33 | def __str__(self): |
sbc@chromium.org | 217330f | 2015-06-01 22:10:14 +0000 | [diff] [blame] | 34 | out = 'Command %r returned non-zero exit status %s' % ( |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 35 | ' '.join(self.cmd), self.returncode) |
| 36 | if self.cwd: |
| 37 | out += ' in ' + self.cwd |
Edward Lemur | 7ad1d09 | 2020-03-11 00:58:39 +0000 | [diff] [blame] | 38 | if self.stdout: |
| 39 | out += '\n' + self.stdout.decode('utf-8', 'ignore') |
| 40 | if self.stderr: |
| 41 | out += '\n' + self.stderr.decode('utf-8', 'ignore') |
| 42 | return out |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 43 | |
| 44 | |
maruel@chromium.org | 1d9f629 | 2011-04-07 14:15:36 +0000 | [diff] [blame] | 45 | class CygwinRebaseError(CalledProcessError): |
| 46 | """Occurs when cygwin's fork() emulation fails due to rebased dll.""" |
| 47 | |
| 48 | |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 49 | ## Utility functions |
| 50 | |
| 51 | |
| 52 | def kill_pid(pid): |
| 53 | """Kills a process by its process id.""" |
| 54 | try: |
| 55 | # Unable to import 'module' |
Quinten Yearsley | b2cc4a9 | 2016-12-15 13:53:26 -0800 | [diff] [blame] | 56 | # pylint: disable=no-member,F0401 |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 57 | import signal |
Raul Tambre | e99d4b4 | 2019-05-24 18:34:41 +0000 | [diff] [blame] | 58 | return os.kill(pid, signal.SIGTERM) |
maruel@chromium.org | fb3d324 | 2011-04-01 14:03:08 +0000 | [diff] [blame] | 59 | except ImportError: |
| 60 | pass |
| 61 | |
| 62 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 63 | def get_english_env(env): |
| 64 | """Forces LANG and/or LANGUAGE to be English. |
| 65 | |
| 66 | Forces encoding to utf-8 for subprocesses. |
| 67 | |
| 68 | Returns None if it is unnecessary. |
| 69 | """ |
maruel@chromium.org | c98c0c5 | 2011-04-06 13:39:43 +0000 | [diff] [blame] | 70 | if sys.platform == 'win32': |
| 71 | return None |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 72 | env = env or os.environ |
| 73 | |
| 74 | # Test if it is necessary at all. |
| 75 | is_english = lambda name: env.get(name, 'en').startswith('en') |
| 76 | |
| 77 | if is_english('LANG') and is_english('LANGUAGE'): |
| 78 | return None |
| 79 | |
| 80 | # Requires modifications. |
| 81 | env = env.copy() |
| 82 | def fix_lang(name): |
| 83 | if not is_english(name): |
| 84 | env[name] = 'en_US.UTF-8' |
| 85 | fix_lang('LANG') |
| 86 | fix_lang('LANGUAGE') |
| 87 | return env |
| 88 | |
| 89 | |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 90 | class Popen(subprocess.Popen): |
maruel@chromium.org | 57bf78d | 2011-09-08 18:57:33 +0000 | [diff] [blame] | 91 | """Wraps subprocess.Popen() with various workarounds. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 92 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 93 | - Forces English output since it's easier to parse the stdout if it is always |
| 94 | in English. |
| 95 | - Sets shell=True on windows by default. You can override this by forcing |
| 96 | shell parameter to a value. |
Edward Lesmes | cf06cad | 2020-12-14 22:03:23 +0000 | [diff] [blame] | 97 | - Adds support for DEVNULL to not buffer when not needed. |
maruel@chromium.org | dd9837f | 2011-11-30 01:55:22 +0000 | [diff] [blame] | 98 | - Adds self.start property. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 99 | |
maruel@chromium.org | 57bf78d | 2011-09-08 18:57:33 +0000 | [diff] [blame] | 100 | Note: Popen() can throw OSError when cwd or args[0] doesn't exist. Translate |
| 101 | exceptions generated by cygwin when it fails trying to emulate fork(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 102 | """ |
torne@chromium.org | 434e790 | 2015-09-15 09:57:01 +0000 | [diff] [blame] | 103 | # subprocess.Popen.__init__() is not threadsafe; there is a race between |
| 104 | # creating the exec-error pipe for the child and setting it to CLOEXEC during |
| 105 | # which another thread can fork and cause the pipe to be inherited by its |
| 106 | # descendents, which will cause the current Popen to hang until all those |
| 107 | # descendents exit. Protect this with a lock so that only one fork/exec can |
| 108 | # happen at a time. |
| 109 | popen_lock = threading.Lock() |
| 110 | |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 111 | def __init__(self, args, **kwargs): |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 112 | env = get_english_env(kwargs.get('env')) |
| 113 | if env: |
| 114 | kwargs['env'] = env |
Gavin Mak | 512f3cb | 2023-09-05 18:02:24 +0000 | [diff] [blame] | 115 | if kwargs.get('env') is not None: |
Raul Tambre | e9730d7 | 2020-01-15 19:28:48 +0000 | [diff] [blame] | 116 | # Subprocess expects environment variables to be strings in Python 3. |
| 117 | def ensure_str(value): |
| 118 | if isinstance(value, bytes): |
| 119 | return value.decode() |
| 120 | return value |
| 121 | |
| 122 | kwargs['env'] = { |
| 123 | ensure_str(k): ensure_str(v) |
| 124 | for k, v in kwargs['env'].items() |
| 125 | } |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 126 | if kwargs.get('shell') is None: |
| 127 | # *Sigh*: Windows needs shell=True, or else it won't search %PATH% for |
| 128 | # the executable, but shell=True makes subprocess on Linux fail when it's |
| 129 | # called with a list because it only tries to execute the first item in |
| 130 | # the list. |
| 131 | kwargs['shell'] = bool(sys.platform=='win32') |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 132 | |
Gavin Mak | 512f3cb | 2023-09-05 18:02:24 +0000 | [diff] [blame] | 133 | if isinstance(args, (str, bytes)): |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 134 | tmp_str = args |
| 135 | elif isinstance(args, (list, tuple)): |
| 136 | tmp_str = ' '.join(args) |
| 137 | else: |
| 138 | raise CalledProcessError(None, args, kwargs.get('cwd'), None, None) |
| 139 | if kwargs.get('cwd', None): |
| 140 | tmp_str += '; cwd=%s' % kwargs['cwd'] |
| 141 | logging.debug(tmp_str) |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 142 | |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 143 | try: |
torne@chromium.org | 434e790 | 2015-09-15 09:57:01 +0000 | [diff] [blame] | 144 | with self.popen_lock: |
| 145 | super(Popen, self).__init__(args, **kwargs) |
Raul Tambre | b946b23 | 2019-03-26 14:48:46 +0000 | [diff] [blame] | 146 | except OSError as e: |
maruel@google.com | ef77f9e | 2011-11-24 15:24:02 +0000 | [diff] [blame] | 147 | if e.errno == errno.EAGAIN and sys.platform == 'cygwin': |
| 148 | # Convert fork() emulation failure into a CygwinRebaseError(). |
| 149 | raise CygwinRebaseError( |
| 150 | e.errno, |
| 151 | args, |
| 152 | kwargs.get('cwd'), |
| 153 | None, |
| 154 | 'Visit ' |
| 155 | 'http://code.google.com/p/chromium/wiki/CygwinDllRemappingFailure ' |
| 156 | 'to learn how to fix this error; you need to rebase your cygwin ' |
| 157 | 'dlls') |
luqui@chromium.org | 7f627a9 | 2014-03-28 00:57:44 +0000 | [diff] [blame] | 158 | # Popen() can throw OSError when cwd or args[0] doesn't exist. |
pgervais@chromium.org | fb653b6 | 2014-04-29 17:29:18 +0000 | [diff] [blame] | 159 | raise OSError('Execution failed with error: %s.\n' |
| 160 | 'Check that %s or %s exist and have execution permission.' |
| 161 | % (str(e), kwargs.get('cwd'), args[0])) |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 162 | |
maruel@chromium.org | 94c712f | 2011-12-01 15:04:57 +0000 | [diff] [blame] | 163 | |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 164 | def communicate(args, **kwargs): |
| 165 | """Wraps subprocess.Popen().communicate(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 166 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 167 | Returns ((stdout, stderr), returncode). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 168 | |
szager@chromium.org | e0558e6 | 2013-05-02 02:48:51 +0000 | [diff] [blame] | 169 | - If the subprocess runs for |nag_timer| seconds without producing terminal |
| 170 | output, print a warning to stderr. |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 171 | - 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] | 172 | """ |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 173 | stdin = None |
| 174 | # When stdin is passed as an argument, use it as the actual input data and |
| 175 | # set the Popen() parameter accordingly. |
Gavin Mak | 512f3cb | 2023-09-05 18:02:24 +0000 | [diff] [blame] | 176 | if 'stdin' in kwargs and isinstance(kwargs['stdin'], (str, bytes)): |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 177 | stdin = kwargs['stdin'] |
| 178 | kwargs['stdin'] = PIPE |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 179 | |
maruel@chromium.org | 94c712f | 2011-12-01 15:04:57 +0000 | [diff] [blame] | 180 | proc = Popen(args, **kwargs) |
Edward Lemur | 1556fbc | 2019-08-09 15:24:48 +0000 | [diff] [blame] | 181 | return proc.communicate(stdin), proc.returncode |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 182 | |
| 183 | |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 184 | def call(args, **kwargs): |
| 185 | """Emulates subprocess.call(). |
| 186 | |
Edward Lesmes | cf06cad | 2020-12-14 22:03:23 +0000 | [diff] [blame] | 187 | Automatically convert stdout=PIPE or stderr=PIPE to DEVNULL. |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 188 | In no case they can be returned since no code path raises |
| 189 | subprocess2.CalledProcessError. |
Josip Sokcevic | 252ff1f | 2020-06-01 23:08:00 +0000 | [diff] [blame] | 190 | |
| 191 | Returns exit code. |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 192 | """ |
| 193 | if kwargs.get('stdout') == PIPE: |
Edward Lesmes | cf06cad | 2020-12-14 22:03:23 +0000 | [diff] [blame] | 194 | kwargs['stdout'] = DEVNULL |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 195 | if kwargs.get('stderr') == PIPE: |
Edward Lesmes | cf06cad | 2020-12-14 22:03:23 +0000 | [diff] [blame] | 196 | kwargs['stderr'] = DEVNULL |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 197 | return communicate(args, **kwargs)[1] |
| 198 | |
| 199 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 200 | def check_call_out(args, **kwargs): |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 201 | """Improved version of subprocess.check_call(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 202 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 203 | Returns (stdout, stderr), unlike subprocess.check_call(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 204 | """ |
maruel@chromium.org | 1f063db | 2011-04-18 19:04:52 +0000 | [diff] [blame] | 205 | out, returncode = communicate(args, **kwargs) |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 206 | if returncode: |
| 207 | raise CalledProcessError( |
| 208 | returncode, args, kwargs.get('cwd'), out[0], out[1]) |
| 209 | return out |
| 210 | |
| 211 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 212 | def check_call(args, **kwargs): |
| 213 | """Emulate subprocess.check_call().""" |
| 214 | check_call_out(args, **kwargs) |
| 215 | return 0 |
| 216 | |
| 217 | |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 218 | def capture(args, **kwargs): |
| 219 | """Captures stdout of a process call and returns it. |
| 220 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 221 | Returns stdout. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 222 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 223 | - Discards returncode. |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 224 | - Blocks stdin by default if not specified since no output will be visible. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 225 | """ |
Edward Lesmes | cf06cad | 2020-12-14 22:03:23 +0000 | [diff] [blame] | 226 | kwargs.setdefault('stdin', DEVNULL) |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 227 | |
| 228 | # Like check_output, deny the caller from using stdout arg. |
| 229 | return communicate(args, stdout=PIPE, **kwargs)[0][0] |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 230 | |
| 231 | |
| 232 | def check_output(args, **kwargs): |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 233 | """Emulates subprocess.check_output(). |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 234 | |
maruel@chromium.org | 0bcd1d3 | 2011-04-26 15:55:49 +0000 | [diff] [blame] | 235 | Captures stdout of a process call and returns stdout only. |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 236 | |
maruel@chromium.org | 421982f | 2011-04-01 17:38:06 +0000 | [diff] [blame] | 237 | - Throws if return code is not 0. |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 238 | - Blocks stdin by default if not specified since no output will be visible. |
| 239 | - As per doc, "The stdout argument is not allowed as it is used internally." |
maruel@chromium.org | 4860f05 | 2011-03-25 20:34:38 +0000 | [diff] [blame] | 240 | """ |
Edward Lesmes | cf06cad | 2020-12-14 22:03:23 +0000 | [diff] [blame] | 241 | kwargs.setdefault('stdin', DEVNULL) |
maruel@chromium.org | db59bfc | 2011-11-30 14:03:14 +0000 | [diff] [blame] | 242 | if 'stdout' in kwargs: |
pgervais@chromium.org | 022d06e | 2014-04-29 17:08:12 +0000 | [diff] [blame] | 243 | raise ValueError('stdout argument not allowed, it would be overridden.') |
maruel@chromium.org | 87e6d33 | 2011-09-09 19:01:28 +0000 | [diff] [blame] | 244 | return check_call_out(args, stdout=PIPE, **kwargs)[0] |