• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# -*- coding: utf-8 -*-
2# Copyright 2019 The ChromiumOS Authors
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Helpers/wrappers for the subprocess module for migration to python3."""
7
8
9import subprocess
10
11
12def CheckCommand(cmd):
13    """Executes the command using Popen()."""
14
15    cmd_obj = subprocess.Popen(
16        cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="UTF-8"
17    )
18
19    stdout, _ = cmd_obj.communicate()
20
21    if cmd_obj.returncode:
22        print(stdout)
23        raise subprocess.CalledProcessError(cmd_obj.returncode, cmd)
24
25
26def check_output(cmd, cwd=None):
27    """Wrapper for pre-python3 subprocess.check_output()."""
28
29    return subprocess.check_output(cmd, encoding="UTF-8", cwd=cwd)
30
31
32def check_call(cmd, cwd=None):
33    """Wrapper for pre-python3 subprocess.check_call()."""
34
35    subprocess.check_call(cmd, encoding="UTF-8", cwd=cwd)
36
37
38# FIXME: CTRL+C does not work when executing a command inside the chroot via
39# `cros_sdk`.
40def ChrootRunCommand(chroot_path, cmd, verbose=False):
41    """Runs the command inside the chroot."""
42
43    exec_chroot_cmd = ["cros_sdk", "--"]
44    exec_chroot_cmd.extend(cmd)
45
46    return ExecCommandAndCaptureOutput(
47        exec_chroot_cmd, cwd=chroot_path, verbose=verbose
48    )
49
50
51def ExecCommandAndCaptureOutput(cmd, cwd=None, verbose=False):
52    """Executes the command and prints to stdout if possible."""
53
54    out = check_output(cmd, cwd=cwd).rstrip()
55
56    if verbose and out:
57        print(out)
58
59    return out
60