1# 2# Copyright (C) 2015 The Android Open Source Project 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15# 16import contextlib 17import os 18import subprocess 19 20 21def color_string(string, color): 22 colors = { 23 'green': '\033[92m', 24 'red': '\033[91m', 25 'yellow': '\033[93m', 26 } 27 end_color = '\033[0m' 28 return colors[color] + string + end_color 29 30 31@contextlib.contextmanager 32def cd(path): 33 curdir = os.getcwd() 34 os.chdir(path) 35 try: 36 yield 37 finally: 38 os.chdir(curdir) 39 40 41def call_output(cmd, *args, **kwargs): 42 """Invoke the specified command and return exit code and output. 43 44 This is the missing subprocess.call_output, which is the combination of 45 subprocess.call and subprocess.check_output. Like call, it returns an exit 46 code rather than raising an exception. Like check_output, it returns the 47 output of the program. Unlike check_output, it returns the output even on 48 failure. 49 50 Returns: Tuple of (exit_code, output). 51 """ 52 proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, 53 stderr=subprocess.STDOUT, *args, **kwargs) 54 out, _ = proc.communicate() 55 return proc.returncode, out 56