michael@0: # Copyright (c) 2012 The Chromium Authors. All rights reserved. michael@0: # Use of this source code is governed by a BSD-style license that can be michael@0: # found in the LICENSE file. michael@0: michael@0: """A wrapper for subprocess to make calling shell commands easier.""" michael@0: michael@0: michael@0: import logging michael@0: import subprocess michael@0: michael@0: michael@0: def RunCmd(args, cwd=None): michael@0: """Opens a subprocess to execute a program and returns its return value. michael@0: michael@0: Args: michael@0: args: A string or a sequence of program arguments. The program to execute is michael@0: the string or the first item in the args sequence. michael@0: cwd: If not None, the subprocess's current directory will be changed to michael@0: |cwd| before it's executed. michael@0: michael@0: Returns: michael@0: Return code from the command execution. michael@0: """ michael@0: logging.info(str(args) + ' ' + (cwd or '')) michael@0: p = subprocess.Popen(args=args, cwd=cwd) michael@0: return p.wait() michael@0: michael@0: michael@0: def GetCmdOutput(args, cwd=None, shell=False): michael@0: """Open a subprocess to execute a program and returns its output. michael@0: michael@0: Args: michael@0: args: A string or a sequence of program arguments. The program to execute is michael@0: the string or the first item in the args sequence. michael@0: cwd: If not None, the subprocess's current directory will be changed to michael@0: |cwd| before it's executed. michael@0: shell: Whether to execute args as a shell command. michael@0: michael@0: Returns: michael@0: Captures and returns the command's stdout. michael@0: Prints the command's stderr to logger (which defaults to stdout). michael@0: """ michael@0: logging.info(str(args) + ' ' + (cwd or '')) michael@0: p = subprocess.Popen(args=args, cwd=cwd, stdout=subprocess.PIPE, michael@0: stderr=subprocess.PIPE, shell=shell) michael@0: stdout, stderr = p.communicate() michael@0: if stderr: michael@0: logging.critical(stderr) michael@0: logging.info(stdout[:4096]) # Truncate output longer than 4k. michael@0: return stdout