• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# -*- coding: utf-8 -*-
2# Copyright 2019 The Chromium OS Authors. All rights reserved.
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
8from __future__ import print_function
9
10import subprocess
11
12
13def CheckCommand(cmd):
14  """Executes the command using Popen()."""
15
16  cmd_obj = subprocess.Popen(
17      cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding='UTF-8')
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
50def ExecCommandAndCaptureOutput(cmd, cwd=None, verbose=False):
51  """Executes the command and prints to stdout if possible."""
52
53  out = check_output(cmd, cwd=cwd).rstrip()
54
55  if verbose and out:
56    print(out)
57
58  return out
59