Hung-Te Lin | 0e0f936 | 2015-11-18 18:18:05 +0800 | [diff] [blame^] | 1 | #!/usr/bin/python |
| 2 | # |
| 3 | # Copyright 2015 The Chromium OS Authors. All rights reserved. |
| 4 | # Use of this source code is governed by a BSD-style license that can be |
| 5 | # found in the LICENSE file. |
| 6 | |
| 7 | from __future__ import print_function |
| 8 | |
| 9 | import logging |
| 10 | from subprocess import Popen, PIPE |
| 11 | |
| 12 | import factory_common # pylint: disable=W0611 |
| 13 | from cros.factory.utils.type_utils import Obj |
| 14 | |
| 15 | |
| 16 | # TODO(hungte) Deprecate this by dut.Shell |
| 17 | def Shell(cmd, stdin=None, log=True): |
| 18 | """Run cmd in a shell, return Obj containing stdout, stderr, and status. |
| 19 | |
| 20 | The cmd stdout and stderr output is debug-logged. |
| 21 | |
| 22 | Args: |
| 23 | cmd: Full shell command line as a string, which can contain |
| 24 | redirection (popes, etc). |
| 25 | stdin: String that will be passed as stdin to the command. |
| 26 | log: log command and result. |
| 27 | """ |
| 28 | process = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True) |
| 29 | stdout, stderr = process.communicate(input=stdin) # pylint: disable=E1123 |
| 30 | if log: |
| 31 | logging.debug('running %s' % repr(cmd) + |
| 32 | (', stdout: %s' % repr(stdout.strip()) if stdout else '') + |
| 33 | (', stderr: %s' % repr(stderr.strip()) if stderr else '')) |
| 34 | status = process.poll() |
| 35 | return Obj(stdout=stdout, stderr=stderr, status=status, success=(status == 0)) |