1#
2# Copyright 2016 - 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 logging
17import subprocess
18
19STDOUT = 'stdouts'
20STDERR = 'stderrs'
21EXIT_CODE = 'return_codes'
22
23
24def RunCommand(command):
25    """Runs a unix command and stashes the result.
26
27    Args:
28        command: the command to run.
29    Returns:
30        code of the subprocess.
31    """
32    proc = subprocess.Popen(
33        command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
34    (stdout, stderr) = proc.communicate()
35    if proc.returncode != 0:
36        logging.error('Fail to execute command: %s  '
37                      '(stdout: %s\n  stderr: %s\n)' % (command, stdout,
38                                                        stderr))
39    return proc.returncode
40
41
42def ExecuteOneShellCommand(cmd):
43    """Execute one shell command and return (stdout, stderr, exit_code).
44
45    Args:
46        cmd: string, a shell command
47
48    Returns:
49        tuple(string, string, int), containing stdout, stderr, exit_code of the shell command
50    """
51    p = subprocess.Popen(
52        str(cmd), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
53    stdout, stderr = p.communicate()
54    return (stdout, stderr, p.returncode)
55
56
57def ExecuteShellCommand(cmd):
58    """Execute one shell cmd or a list of shell commands.
59
60    Args:
61        cmd: string or a list of strings, shell command(s)
62
63    Returns:
64        dict{int->string}, containing stdout, stderr, exit_code of the shell command(s)
65    """
66    if not isinstance(cmd, list):
67        cmd = [cmd]
68
69    results = [ExecuteOneShellCommand(command) for command in cmd]
70    stdout, stderr, exit_code = zip(*results)
71    return {STDOUT: stdout, STDERR: stderr, EXIT_CODE: exit_code}
72